8000 移动端使用数字键盘 · Issue #117 · xinglie/xinglie.github.io · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

移动端使用数字键盘 #117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

< 8000 /div>
Open
xinglie opened this issue Jul 25, 2024 · 0 comments
Open

移动端使用数字键盘 #117

xinglie opened this issue Jul 25, 2024 · 0 comments

Comments

@xinglie
Copy link
Owner
xinglie commented Jul 25, 2024

以下是2020年的测试及方案

网上唤起数字键盘的方案有很多,根据网上的方案和自己的实践,总结如下

手上仅有ios设备(iPhone 6s Plus,sv:13.4.1),未测试android

文本

<input type="text"/>

type="text"输入框通常唤起用户的默认键盘,比如我用的ios笔画输入法,唤起时这样
image

这个只是用于对比。

文本+pattern

<inpyt type="text" pattern="[0-9]*"/>

以上代码在ios上可以显示数字键盘

image

尝试加入小数等,ios上则直接切换成普通的文字键盘

tel

<input type="tel" />

image

tel则多了+×#这几个键

tel+pattern

<input type="tel" pattern="[0-9]*"/>

这个效果同tel
image

number

<input type="number"/>

image

包含小数点等,也能切换到其它输入法上

number+pattern

<input type="number" pattern="[0-9]*"/>

这个效果同type="text"带pattern的效果

image

inputmode="numeric"

<input type="text" inputmode="numeric"/>

这个效果同type="text"带pattern的效果

image

container+模拟

image

实在不行,咱就自己做,就像上图这样的,输入界面,输入键盘我自己搞这总行了吧?
这种对于输入密码、金额等场景下确实也是合适的,但是因为无光标或有些模拟的光标不如原生的效果,如果输入错误只能从后删除,不能像原生input那样可以改变光标的位置仅删除光标处的数字。
模拟的场景对于高要求的UI,少量的数字输入是可行的,再复杂了那真不如用原生的,因为要处理的细节还挺多的。

关于取值

综上,最后在实践中使用<input type="number"/>进行数字的输入
在使用过程中,type="number"除了数字和小数点外,+,-,e这三个字符也可以输入,因为可以输入科学计数,比如输入 2e5这样的数字
如果用户输入的是合法的数字(包含科学计数的形式)形式,则我们可以使用input.value拿到原始值,也可以使用input.valueAsNumber拿到转换后的数字,如
image
image

简便起见,对于type="number"的使用取valueAsNumber来做为最终用户的输入。
如果用户输入是非法的,不能转换成数字的,比如+2eeee333这样的输入。
image
image

我们可以看到通过value并不能取到用户的原始输入+2eeee333,同时valueAsNumber也不能转换成合法数字,返回NaN

这次的需求需要根据输入框有没有用户的输入进行不同的界面展示,那我要检测输入框内有没有用户的输入该如何办?

image

当输入框无用户输入时,此时
image

value是空,valueAsNumber依然是NaN,所以我们就不能很好的区分初始化时的无值和用户输入非法值。

这时候就需要checkValidity方法进行处理了:https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

对于无输入的情况:
image
image

虽然value是空,valueAsNumber为NaN,但是checkValidity是true

对于非法的情况
image
image

虽然value是空,valueAsNumber为NaN,但是checkValidity是false

我们可以通过这些API进行识别是否是合法数字和用户是否进行了输入等处理。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant
0