- 任何可以获得焦点的元素都可以触发keypress,但只有可编辑区域才可能触发textInput事件。例如:checkbox框上按下键盘(不是鼠标哦!!!)只会触发keypress事件,但是不会触发textInput
<input type="checkbox" name="" id="c" value="" />
<script type="text/javascript">
var c = document.getElementById('c');
c.addEventListener('keypress',function(e){
console.log("c");
console.log(e)
},false);
c.addEventListener('textInput',function(e){
console.log("c");
console.log(e)
},false);
</script>
此时,只会触发keypress事件。
![](https://img.haomeiwen.com/i10937452/baa0e09c82314852.jpg)
- textInput事件只会在用户按下能够输入实际字符的键时才会触发,而keypress事件则在按下那些影响文本显示的键时也会触发(例如退格键)。(这个没有试验出来)尝试修改为中文输入法试一下。
<input type="text" name="a" id="a" value="" />
<script type="text/javascript">
var a = document.getElementById('a');
a.addEventListener('keypress',function(e){
console.log("a");
console.log(e)
},false);
a.addEventListener('textInput',function(e){
console.log("a");
console.log(e)
},false);
</script>
此时,只会触发textInput事件。
![](https://img.haomeiwen.com/i10937452/7ebe0e6c30c2715d.png)
![](https://img.haomeiwen.com/i10937452/535c785c18b6c686.png)
网友评论