开发者

html5 input type number: detect whether spinbox or not (and no other features)

In Webkit browsers, an input[type=number] has a spinbox control:

html5 input type number: detect whether spinbox or not (and no other features)

However, Safari does not follow some other input[type=number] rules, like enforcing that only numeric characters are entered. Hence, Modernizr detects that Safari does not support input[type=number].

I have very particular needs for number-input width, and when there's a spinbox I make the width 2.7em and without it (like in Firefox), the width need only be 1.7em. So Chrome and Firefox both look fine. But Safari puts in a spinbox but doesn't follow any other rules, so it gets the 1.7em width and looks like this:

html5 input type number: detect whether spinbox or not (and no other features)

I only care if 开发者_如何学Gothere's a spinbox control. I don't care about any of the other input[type=number] rules that Safari is flouting. Safari is playing by the only rule I care about. How do I detect that?


I suggest hiding the spinbox when Modernizr doesn't detect support for number inputs:

JS:

if (!Modernizr.inputtypes.number) {
    $('body').addClass('no-number-input');
}

CSS:

.no-number-input input::-webkit-outer-spin-button,
.no-number-input input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0; 
}

If you really want to detect whether the spinbox is visible you can do something like:

window.getComputedStyle(input, '-webkit-inner-spin-button').getPropertyValue('-webkit-appearance') != 'none'

where input is a "raw" element, although this may not be very reliable, e.g. in Safari for Windows.


if (Modernizr.inputtypes.number) {
  $('input[type=number]').width('2.7em');
} else {
  $('input[type=number]').width('1.7em');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜