输入框输入中文显示字数问题解决
问题:输入中文时 如xin 新 会显示字数:1 2 3 1 这不是我们想要的 在输入xin 新 时 应该是 1 不能把 xin 计算进去

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- <button>点击</button> -->
<input type="text" />
<span></span>
<script>
const input = document.querySelector('input')
let isChinese = false
input.addEventListener('compositionstart', function (ev) {
// 该事件类型与 input 类似的,都是在用户进行输入时被触发
// 区别在于 该事件在针对中文输入时,只有文字确定后才会触发
// console.log("文字输入了");
// 该事件只有在输入中文时才会触发
console.log('你正在输入的中文...')
isChinese = true
})
input.addEventListener('compositionend', function (ev) {
// 该事件类型与 input 类似的,都是在用户进行输入时被触发
// 区别在于 该事件在针对中文输入时,只有文字确定后才会触发
// console.log("文字输入了");
// 该事件只有在输入中文时才会触发
console.log('你正在输入的中文输入结束了...')
document.querySelector('span').innerHTML = this.value.length
isChinese = false
})
input.addEventListener('input', function () {
if (isChinese) return
document.querySelector('span').innerHTML = this.value.length
})
</script>
</body>
</html>
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>Document</title> | |
| </head> | |
| <body> | |
| <!-- <button>点击</button> --> | |
| <input type="text" /> | |
| <span></span> | |
| <script> | |
| const input = document.querySelector('input') | |
| let isChinese = false | |
| input.addEventListener('compositionstart', function (ev) { | |
| // 该事件类型与 input 类似的,都是在用户进行输入时被触发 | |
| // 区别在于 该事件在针对中文输入时,只有文字确定后才会触发 | |
| // console.log("文字输入了"); | |
| // 该事件只有在输入中文时才会触发 | |
| console.log('你正在输入的中文...') | |
| isChinese = true | |
| }) | |
| input.addEventListener('compositionend', function (ev) { | |
| // 该事件类型与 input 类似的,都是在用户进行输入时被触发 | |
| // 区别在于 该事件在针对中文输入时,只有文字确定后才会触发 | |
| // console.log("文字输入了"); | |
| // 该事件只有在输入中文时才会触发 | |
| console.log('你正在输入的中文输入结束了...') | |
| document.querySelector('span').innerHTML = this.value.length | |
| isChinese = false | |
| }) | |
| input.addEventListener('input', function () { | |
| if (isChinese) return | |
| document.querySelector('span').innerHTML = this.value.length | |
| }) | |
| </script> | |
| </body> | |
| </html> | |
浙公网安备 33010602011771号