当前位置:网站首页>表单文本框的使用(二) 输入过滤(合成事件)
表单文本框的使用(二) 输入过滤(合成事件)
2022-07-05 20:31:00 【赤蓝紫】
表单文本框的使用(二) 输入过滤(合成事件)
输入过滤
屏蔽字符
情景:输入框需要限制出现的字符,比如只能是数字。
输入框本身是没有这个功能的,但是我们可以通过JavaScript来实现。 我们能实现向输入框中输入字符,依靠的是键盘事件,所以可以通过添加键盘事件,然后根据事件对象的信息来判断符不符合条件,不符合条件,就通过event.preventDefault阻止默认事件,即阻止输入。
<body>
<div class="input-box">
<input type="text" size="10" maxlength="10">
</div>
<script>
const ipt = document.getElementsByTagName('input')[0]
ipt.addEventListener('keypress', (e) => {
console.log(e.key)
if (!/^\d/.test(e.key)) {
e.preventDefault()
}
})
</script>
</body>
上面我们添加的键盘事件是keypress,因为keyup是键盘抬起事件,这个时候已经输入到输入框里了,没有作用;而keydown会识别功能键,所以使用时还得考虑让功能键通过,不然就没法删除输入的内容了。另外,keypress支持区分大小写。

处理剪切板
上面我们已经实现只能输入数字了,但是如果我们从外部复制了非数字的数据,粘贴到文本框里就会突破我们的输入过滤。

这时候就需要通过剪切板事件来加强我们的输入过滤了(HTML5增加了剪切板事件)
copy:复制操作发生时触发cut:剪切操作发生时触发paste:粘贴操作发生时触发
这三个事件都有添加前缀before的操作发生前触发版本,但是不常用,也不知道有什么具体使用情境。阻止事件也只能在发生时触发的三个事件中阻止。
怎么获取剪切板的数据呢? 可以通过event对象上的clipboardData对象来获取,为防止未经授权访问剪切板,只能在剪切板事件期间访问clipboardData对象。
clipboardData对象上有3个方法:getDate、setData、clearData。
const ipt = document.getElementsByTagName('input')[0]
ipt.addEventListener('keypress', (e) => {
console.log(e.key)
if (!/^\d/.test(e.key)) {
e.preventDefault()
}
})
ipt.addEventListener('copy', (e) => {
// e.clipboardData.setData第一个参数是格式,第二个参数是复制的内容
e.clipboardData.setData('text/plain', '复制了假数据')
// 屏蔽掉默认事件,实现复制假数据
e.preventDefault()
})
ipt.addEventListener('paste', (e) => {
// 读取剪切板的数据
const text = e.clipboardData.getData('text/plain')
// 不满足条件不让粘贴
if (!/^\d/.test(text)) {
e.preventDefault()
}
})
这样子,就能实现即使是粘贴的数据也要是数字才能输入到输入框了。

处理中文、日语等输入法

当我们使用输入法时,还是会绕过了我们的只能输入数字的限制。
这里引入一个比较有意思的知识点合成事件
中文这种是需要同时按下多个键才能输入一个字符的。合成事件就是用来检测和控制这种输入,输入的字符在事件对象的data中。
compositionstart:表示输入即将开始,此时data为空串compositionupdate:新字符插入时触发,此时data为输入的字符compositionend:表示即将恢复正常的键盘输入,此时data为要输入到输入框的文本
实践:
const ipt = document.getElementsByTagName('input')[0]
ipt.addEventListener('compositionstart', (e) => {
console.log('%c%s', 'color: red;font-size: 16px;', 'conpositionstart')
console.log(e.data)
})
ipt.addEventListener('compositionupdate', (e) => {
console.log('%c%s', 'color: blue;font-size: 16px;', 'compositionupdate')
console.log(e.data)
})
ipt.addEventListener('compositionend', (e) => {
console.log('%c%s', 'color: purple;font-size: 16px;', 'compositionend')
})

所以说我们可以在合成事件结束的时候,即compositionend的事件处理函数中,把输入的中文给去掉,就能够不允许把汉字输进去。
const ipt = document.getElementsByTagName('input')[0]
ipt.addEventListener('compositionend', (e) => {
// 去掉后几位
e.target.value = e.target.value.slice(0, -e.data.length)
})

完整代码
<body>
<div class="input-box">
<input type="text" size="10" maxlength="10">
</div>
<script>
const ipt = document.getElementsByTagName('input')[0]
ipt.addEventListener('keypress', (e) => {
console.log(e.key)
if (!/^\d/.test(e.key)) {
e.preventDefault()
}
})
ipt.addEventListener('paste', (e) => {
// 读取剪切板的数据
const text = e.clipboardData.getData('text/plain')
// 不满足条件不让粘贴
if (!/^\d/.test(text)) {
e.preventDefault()
}
})
ipt.addEventListener('compositionend', (e) => {
// 去掉后几位
e.target.value = e.target.value.slice(0, -e.data.length)
})
</script>
</body>
边栏推荐
- 【数字IC验证快速入门】3、数字IC设计全流程介绍
- sun. misc. Base64encoder error reporting solution [easy to understand]
- CCPC 2021 Weihai - G. shinyruo and KFC (combination number, tips)
- 欢迎来战,赢取丰厚奖金:Code Golf 代码高尔夫挑战赛正式启动
- model方法
- CCPC 2021威海 - G. Shinyruo and KFC(组合数,小技巧)
- Ros2 topic [01]: installing ros2 on win10
- Leetcode brush question: binary tree 14 (sum of left leaves)
- y57.第三章 Kubernetes从入门到精通 -- 业务镜像版本升级及回滚(三十)
- js方法传Long类型id值时会出现精确损失
猜你喜欢

【数字IC验证快速入门】6、Questasim 快速上手使用(以全加器设计与验证为例)

解决php无法将string转换为json的办法

Rainbow 5.7.1 supports docking with multiple public clouds and clusters for abnormal alarms

A way to calculate LNX

A solution to PHP's inability to convert strings into JSON

Fundamentals - configuration file analysis
![[quick start of Digital IC Verification] 9. Finite state machine (FSM) necessary for Verilog RTL design](/img/32/a156293f145417eeae8d93c539ca55.png)
[quick start of Digital IC Verification] 9. Finite state machine (FSM) necessary for Verilog RTL design

Leetcode skimming: binary tree 16 (path sum)

Solve the problem that the database configuration information under the ThinkPHP framework application directory is still connected by default after modification

【数字IC验证快速入门】3、数字IC设计全流程介绍
随机推荐
计算lnx的一种方式
Codeforces Round #804 (Div. 2) - A, B, C
1、强化学习基础知识点
Zero cloud new UI design
点云文件的.dat文件读取保存
港股将迎“最牛十元店“,名创优品能借IPO突围?
[quick start of Digital IC Verification] 3. Introduction to the whole process of Digital IC Design
信息学奥赛一本通 1340:【例3-5】扩展二叉树
2.8、项目管理过程基础知识
[quick start of Digital IC Verification] 6. Quick start of questasim (taking the design and verification of full adder as an example)
July 4, 2022 - July 10, 2022 (UE4 video tutorial MySQL)
Leetcode: binary tree 15 (find the value in the lower left corner of the tree)
DP: tree DP
【刷题记录】1. 两数之和
Dry goods navigation in this quarter | Q2 2022
sun. misc. Base64encoder error reporting solution [easy to understand]
ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development
Leetcode(347)——前 K 个高频元素
如何形成规范的接口文档
Hongmeng OS' fourth learning