下面的代碼,是我們再做一個正則的判斷,不讓輸入我們列舉的特殊符號。大部分情況下是沒有問題的,可是在少數人的電腦上,發現,在輸入中文的時候,會有重複的情況。請看下面的動圖
1 <p>輸入中文,只使用oninput和onkeyup的方式</p> 2 <input type="text" name="" id="input" placeholder="不能輸入特殊符號" 3 oninput="value=value.replace(/[`~!#$%^&*()_\+=<>?:'{}|~!#¥%……&*()={}|《》?:“”【】、;‘’,。、\s+]/g, '')">
我們猜想,這個和輸入法有關,經過查找,發現了確實是這樣的。具體問題請自行百度,或者查看鏈接。貌似是微軟的輸入法的問題,我試了搜狗輸入法沒問題。但是不能所用的用戶捨棄微軟的輸入法。前端其實也是有解決辦法的,就是使用
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 </head> 9 10 <body> 11 <p>輸入中文,只使用oninput和onkeyup的方式</p> 12 <input type="text" name="" id="input1" placeholder="不能輸入特殊符號" 13 oninput="value=value.replace(/[`~!#$%^&*()_\+=<>?:'{}|~!#¥%……&*()={}|《》?:“”【】、;‘’,。、\s+]/g, '')" /> 14 <p>輸入中文,使用compositionend事件監聽</p> 15 <input type="text" name="" id="" class="input2" placeholder="不能輸入特殊符號" /> 16 </body> 17 <script> 18 let input = document.querySelector('.input2'); 19 20 input.addEventListener('compositionstart', function (event) { 21 inputLock = true; 22 console.log('compositionstart', checkLength(event.target.value), event); 23 }); 24 input.addEventListener('compositionend', function (event) { 25 inputLock = false; 26 console.log('compositionend', checkLength(event.target.value), event); 27 }); 28 function checkLength(data){ 29 console.log(data) 30 input.value = data.replace(/[`~!#$%^&*()_\+=<>?:'{}|~!#¥%……&*()={}|《》?:“”【】、;‘’,。、\s+]/g, '') 31 } 32 </script> 33 34 </html>
通過這個事件觸發的話,就不會出現上面GIF圖的問題了。