javascript iOS5 默认显示数字小键盘,不使用 type="number" 或 type="tel"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8222528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:41:33  来源:igfitidea点击:

iOS5 show numeric keypad by default without using type="number" or type="tel"

javascriptiphonehtmlios5input

提问by marissajmc

With the release of iOS5, Apple has added their own validation to input type="number" form fields. This is causing some issues; see this question below which sums it up:

随着 iOS5 的发布,Apple 为 input type="number" 表单字段添加了自己的验证。这导致了一些问题;请参阅下面的这个问题,总结一下:

Input type='number' new validation removes leading zeros and formats number in Safari for iPhone iOS5 and latest Safari for Mac

Input type='number' 新验证删除了 Safari for iPhone iOS5 和最新的 Safari for Mac 中的前导零和格式数字

Although input type="tel" works to bring up a numeric keypad on the iphone, it's the telephone keypadwhich has no decimal points.

尽管 input type="tel" 可以在 iphone 上调出数字键盘,但它是没有小数点的电话键盘

Is there a way to set the numeric keypad as default using html/js? This not an iphone app. At minimum I need numbers and a decimal point in the keypad.

有没有办法使用 html/js 将数字键盘设置为默认值?这不是 iPhone 应用程序。至少我需要键盘上的数字和小数点。

Update

更新

Number input fields in Safari 5.1/iOS 5 only accept digits and decimal points. The default value for one of my inputs is $500,000. This is resulting in Safari showing a blank input field because $ , % are invalid characters.

Safari 5.1/iOS 5 中的数字输入字段只接受数字和小数点。我的输入之一的默认值是$500,000。这导致 Safari 显示空白输入字段,因为 $ , % 是无效字符。

Furthermore, when I run my own validation onblur, Safari clears the input field because I'm adding a $ to the value.

此外,当我运行自己的验证时onblur,Safari 会清除输入字段,因为我在值中添加了 $。

Thus Safari 5.1/iOS5's implementation of input type="number" has rendered it unusable.

因此,Safari 5.1/iOS5 的 input type="number" 实现使其无法使用。

jsfiddle

提琴手

Try it here - http://jsfiddle.net/mjcookson/4ePeE/The default value of $500,000 won't appear in Safari 5.1, but if you remove the $ and , symbols, it will. Frustrating.

在这里尝试 - http://jsfiddle.net/mjcookson/4ePeE/默认值 $500,000 不会出现在 Safari 5.1 中,但如果您删除 $ 和 , 符号,它会出现。令人沮丧。

采纳答案by marissajmc

Working solution: Tested on iPhone 5, Android 2.3, 4

工作解决方案:在 iPhone 5、Android 2.3、4 上测试

Tadeck's solution (bounty winner) of using a <span>to contain the input field symbols and place a formatted <span>on top of the currency input is essentially what I ended up doing.

Tadeck 的解决方案(赏金赢家)使用 a<span>来包含输入字段符号并将格式化的<span>放在货币输入之上,这基本上是我最终要做的。

My final code is different and shorter however so I'm posting it here. This solution resolves the iOS5 validation issue of $ , % symbols inside input fields and so input type="number"can be used by default.

但是,我的最终代码不同且更短,因此我将其发布在这里。此解决方案解决了 iOS5 输入字段中 $ 、 % 符号的验证问题,因此input type="number"可以默认使用。

Symbol field eg. "xx %" "xx years"

符号字段,例如。"xx %" "xx 年"

<input name="interest-rate" value="6.4" maxlength="4" min="1" max="20" />
<span class="symbol">%</span>
  • Simply use a number input field and a span outside the input to display the symbol.
  • 只需使用数字输入字段和输入外的跨度来显示符号。

Currency field eg. "$xxx,xxx"

货币字段,例如。“$xxx,xxx”

<span id="formatted-currency">0,000</span>
<input id="currency-field" type="number" name="loan-amount" value="500000" maxlength="8" min="15000" max="10000000" />
  • Position the span on top of the currency input and set the input to display:none
  • When a user clicks/taps on the span, hide the span and show the input. If you position the span perfectly the transition is seamless.
  • The number input type takes care of the validation.
  • On blur and submit of the input, set the span html to be the input's value. Format the span. Hide the input and show the span with the formatted value.
  • 将跨度放置在货币输入的顶部并将输入设置为 display:none
  • 当用户单击/点击跨度时,隐藏跨度并显示输入。如果您完美地定位跨度,则过渡是无缝的。
  • 数字输入类型负责验证。
  • 在输入的模糊和提交时,将 span html 设置为输入的值。格式化跨度。隐藏输入并显示具有格式化值的跨度。

$('#formatted-currency').click(function(){
    $(this).hide();
    $('#currency-field').show().focus();
});
$('#currency-field').blur(function(){
    $('#formatted-currency').html(this.value);
    $('#formatted-currency').formatCurrency({
        roundToDecimalPlace : -2
    });
    $(this).hide();
    $('#formatted-currency').show();
});
// on submit
$('#formatted-currency').html($('#currency-field').val());
$('#formatted-currency').formatCurrency({
    roundToDecimalPlace : -2
});
$('#currency-field').hide();
$('#formatted-currency').show();

回答by Tadeck

Styling the field to contain symbols

样式化字段以包含符号

When it comes to including the symbols within this numberfield, you can use some walkaround like that:

当涉及在此number字段中包含符号时,您可以使用一些类似的方法:

HTML:

HTML:

<span id="number-container">
    <input type="number" name="number" id="number-field" value="500" />
    <span id="number-container-symbol">$</span>
</span>

CSS:

CSS:

#number-container {
    position: relative;
}
#number-container-symbol {
    left: 5pt;
    position: absolute;
    top: 0px;
}
#number-field {
    background-color: transparent;
    padding-left: 10pt;
}

Treat it as a proof of concept. See this jsfiddlefor a live example. It looks like that in Chrome:

将其视为概念证明。请参阅此 jsfiddle以获取实时示例。在 Chrome 中看起来是这样的:

enter image description here

在此处输入图片说明

Defining smaller granularity

定义更小的粒度

Based on the documentation on number input (Editor's Draft), to define granularityyou need to add step="<some-floating-point-number>"attribute to the <input>tag:

根据关于数字输入 (Editor's Draft) 的文档,要定义粒度,您需要向标签添加step="<some-floating-point-number>"属性<input>

<input type="number" name="number" value="500.01" step="0.01" />

and it will work in many modern browsers. See this jsfiddlefor tests.

它将在许多现代浏览器中工作。请参阅此 jsfiddle进行测试。

Conclusion

结论

You should be able to style it to contain symbols you need. There is also a feature that, according to documentation, enables support for floating-point numbers.

您应该能够对其进行样式设置以包含您需要的符号。根据文档,还有一个功能可以支持浮点数。

Alternative solution - empty field in front of something else

替代解决方案 - 其他东西前面的空白字段

You can also trick someone into believing he is seeing content of the input field, but show him something else behind the field (this is some extension of my original solution). Then if someone taps the field, you can propagate proper value etc., then go back to the previous state on blur. See this code (live example on jsfiddle- blue color means you are looking at something that is not within the field):

您还可以欺骗某人相信他正在看到输入字段的内容,但向他展示该字段后面的其他内容(这是我原始解决方案的一些扩展)。然后,如果有人点击该字段,您可以传播适当的值等,然后在模糊时返回到先前的状态。请参阅此代码(jsfiddle 上的实时示例- 蓝色表示您正在查看不在该领域内的内容):

// store original value from INPUT tag in jQuery's .data()
var input_field = jQuery('#number-field');
var display_span = jQuery('#number-container-value');
var base_val = parseFloat(input_field.val());
input_field.data('storedVal', base_val);
input_field.val('');
display_span.html(base_val);

// react to field gaining and losing focus
jQuery('#number-field').on('focus', function(event){
    var el = jQuery(this);
    var display = jQuery('#number-container-value');
    if (typeof el.data('storedVal') != 'undefined'){
        el.val(el.data('storedVal'));
    };
    display.html('');
}).on('blur', function(event){
    var el = jQuery(this);
    var display = jQuery('#number-container-value');
    var new_val = parseFloat(el.val());
    el.data('storedVal', new_val);
    display.html(new_val);
    el.val('');
});

(the full code with styling is on the mentioned jsfiddle). The code needs shortening & cleaning up, but it is a proof of concept. Try it and share your findings, please.

(带有样式的完整代码在提到的 jsfiddle 上)。代码需要缩短和清理,但它是概念证明。请尝试并分享您的发现。

回答by Dad

Why not put the $ outside the input field (as a label). Or the percent sign to the right of the input field? Seems like that'd solve your issue and you'd be able to use input type="number" and it'd just work.

为什么不将 $ 放在输入字段之外(作为标签)。还是输入字段右侧的百分号?似乎这可以解决您的问题,并且您可以使用 input type="number" 并且它可以正常工作。

回答by Ahmed Nuaman

You're stuck between a rock and a hard place. Until there's a place in the HTML spec for type="currency"(and that'll probably never happen cos of the different ways different countries write currency), you're going to have to use some JS magic to get around the problem.

你被困在岩石和坚硬的地方之间。除非在 HTML 规范中有一个位置type="currency"(并且这可能永远不会发生,因为不同国家/地区编写货币的方式不同),您将不得不使用一些 JS 魔法来解决这个问题。

Of course number nor telephone won't be the best idea, however by using a bit of JS cunning I've come up with this solution:

当然,电话号码和电话都不是最好的主意,但是通过使用一些 JS 技巧,我想出了这个解决方案:

var i   = document.getElementById( 'input' );

i.onblur    = function()
{
    i.type  = 'text';

    i.value = number_format( i.value );
}

i.onfocus   = function()
{
    var v   = Number( i.value.replace( /\D/, '' ) );

    i.type  = 'number';

    i.value = v > 0 ? v : '';
}

Simply I swap the type of the input depending on focus/blur, this means that once the user has left the text field, we can format its ass. When the user returns, we take the value, if there's one that's > 0 and we stick it back in as a number. Here's the working test, I hope it helps: http://jsfiddle.net/ahmednuaman/uzYQA/

简单地我根据焦点/模糊交换输入的类型,这意味着一旦用户离开文本字段,我们就可以格式化它的屁股。当用户返回时,我们取值,如果有一个大于 0 的值,我们将它作为一个数字放回去。这是工作测试,我希望它有帮助:http: //jsfiddle.net/ahmednuaman/uzYQA/

回答by robocat

The following pops up the numeric keyboard for iPad with iOS5, allows anycharacter to be typed, and allows anyvalue to be set:

下面弹出iOS5的iPad数字键盘,可以输入任意字符,可以设置任意值:

<input type="text" pattern="\d*">

However it is ugly, fragile (probably will break in future ...), and doesn't work on iPhone (iPhone shows the numeric keypad that only allows 0 to 9). The solution only seems to work using the pattern \d*or its equivalent [0-9]*.

然而,它丑陋、脆弱(将来可能会坏掉……),并且在 iPhone 上不起作用(iPhone 显示的数字小键盘只允许 0 到 9)。该解决方案似乎只适用于模式\d*或其等效项[0-9]*

Maybe better to use type="tel"which seems to act the same.

也许更好地使用type="tel"它似乎表现相同。

回答by Snorvarg

I had a similar problem, and came up with this dead-ugly js solution, forcing the iPad to popup the numeric keypad.

我也遇到了类似的问题,想出了这个丑陋的js解决方案,迫使iPad弹出数字小键盘。

My problem was that safari filter away everything except digits when the form is posted, and I need various extra characters, for example "3/7", or "65$".

我的问题是 safari 在发布表单时过滤掉除数字之外的所有内容,我需要各种额外的字符,例如“3/7”或“65$”。

var elem = document.getElementById('MathAnswer');
elem.type = 'number';

elem.onfocus = function() {
  setTimeout(function() {
    elem.type = 'text'; 
  }, 1);
};

It simply set the input type back to 'text' afteriPad has shown the numeric keypad, and voila, safari no longer removes any non-digits.

它只是iPad 显示数字小键盘后将输入类型设置回“文本” ,瞧,safari 不再删除任何非数字。

Hope it helps someone!

希望它可以帮助某人!

回答by rakensi

Your problem would be solved if Safari would support the HTML5 'inputmode' attribute for input elements. Nobody knows if, or when that is going to happen. In the meantime this linkprovides some interesting reading.

如果 Safari 支持输入元素的 HTML5 'inputmode' 属性,您的问题就会得到解决。没有人知道这是否会发生,或者什么时候会发生。与此同时,这个链接提供了一些有趣的阅读。

回答by robocat

We ended up using a hacky solution to enable the numbersandpunctuation keyboard to show when focused which works on an iPhone: we record the keypresses and simulate the value.

我们最终使用了一个 hacky 解决方案来使数字和标点键盘在聚焦时显示,这在 iPhone 上有效:我们记录按键并模拟值。

https://output.jsbin.com/necuzoj/quiet

https://output.jsbin.com/necuzoj/quiet

We tried changing the input type from type=number to type=text on focus, but it was unreliable: (1) the numeric keyboard didn't show 100% of the time, and (2) if a form was was longer than the screen then the auto scrolling to show the focused input was completely stuffed up (sometimes the focused input would be off-screen or under the virtual keyboard).

我们尝试将输入类型从 type=number 更改为 type=text on focus,但这是不可靠的:(1) 数字键盘没有 100% 的时间显示,以及 (2) 如果表单的长度超过screen 然后自动滚动以显示焦点输入完全填满(有时焦点输入会在屏幕外或在虚拟键盘下)。

Showing the numeric keypad (e.g. type=tel) didn't allow the entry of a decimal point or colon.

显示数字小键盘(例如type=tel)不允许输入小数点或冒号。

On an iPad you can just use <input type=text pattern=[0-9]*>to show the numbersandpunctiation keyboard, but that solution doesn't work for an iPhone (an iPhone shows the numeric keypad with no decimal point).

在 iPad 上,您只能使用<input type=text pattern=[0-9]*>显示数字和标点键盘,但该解决方案不适用于 iPhone(iPhone 显示的数字小键盘没有小数点)。

回答by robocat

There is potentially another way around the issue for the iPhone:

iPhone 的问题可能还有另一种解决方法:

<input id="test" TYPE="text" value="5.50" ontouchstart="this.type='number'" onfocus="this.type='text'" />

This changes the type to number beforethe input gets focus when touched (so that the numeric keyboard shows) and then changes the type to text so that the correct value can be edited.

这将在触摸输入获得焦点之前将类型更改为数字(以便数字键盘显示),然后将类型更改为文本,以便可以编辑正确的值。

Getting it working reliably might be hard though e.g. currently touch input but then slide finger off control leaves it as type=number, and I can't think of a way to detect the Next button on keyboard, amongst other issues.

让它可靠地工作可能很困难,例如当前触摸输入但然后将手指滑离控制使其成为 type=number,并且我想不出一种方法来检测键盘上的 Next 按钮,以及其他问题。

回答by robocat

This solution works on iPad and iPhone, and even Next/Previous work. Try http://fiddle.jshell.net/L77Cq/2/show/(or http://jsfiddle.net/L77Cq/to edit).

此解决方案适用于 iPad 和 iPhone,甚至适用于 Next/Previous 工作。尝试http://fiddle.jshell.net/L77Cq/2/show/(或http://jsfiddle.net/L77Cq/进行编辑)。

<!DOCTYPE html>
<head>
<style>
    .riggedinput::-webkit-input-placeholder {
    margin: 0em;
    font: -webkit-small-control;
    color: initial;
    letter-spacing: normal;
    word-spacing: normal;
    line-height: normal;
    text-transform: none;
    text-indent: 0px;
    text-shadow: none;
}
</style>
<script>
    function focused() {
        var test = document.getElementById('test');
        setTimeout(function() { // timeout needed so that keyboard changes to numeric when using Next/Previous keyboard navigation buttons
            if (document.activeElement === test) {
                test.type = 'text';
                test.value = test.placeholder;
                test.placeholder = '';
            }
        }, 1);
    }
    function blurred() {
        var test = document.getElementById('test');
        var value = test.value;
        test.placeholder = value;
        test.value = '';
        test.type = 'number';
    }
    if (!/^(iPhone|iPad|iPod)$/.test(navigator.platform)) alert ('Code specific to Mobile Safari');
</script>
</head>
<body>
    <input>
    <input id="test" type="number" class="riggedinput" placeholder="0.10USD" onfocus="focused()" onblur="blurred()">
    <input>
</body>

It still has the following issues: * If using forms, needs to copy value to a hidden field. * For some reason the page scrolls funny (iPhone address bar hides, iPad Debug Console hides).

它仍然存在以下问题: * 如果使用表单,需要将值复制到隐藏字段。* 由于某种原因,页面滚动很有趣(iPhone 地址栏隐藏,iPad 调试控制台隐藏)。

PS: I found this technique independently of Ahmed Nuaman's comment above (I had tried it in the past, and noticed his comment just now - arrrgh!).

PS:我独立于上述 Ahmed Nuaman 的评论发现了这种技术(我过去曾尝试过,并且刚刚注意到他的评论 - arrrgh!)。