我必须对一个html元素同时使用keypress和keydown处理程序。但是按键和按键都被触发(正如预期的那样)。因此,当我按下一个键时,我在我的竞争div中得到两个字符串。
。只有按下键不允许我复制一个连续的字符串像'aaaaaaa',我已经通过持有'a'按钮进入我的'内容'div。我需要两个处理程序,因为如果我按住一个键,我会在contentdiv中得到一个字母,而不是一个字母数组。这就是为什么我需要这里的按键处理程序。但当另一个活跃时,我真的需要停止其中一个。如何做到这一点。或者如果有其他更好的方法,请告诉我
var editor=document.getElementById('editor');
var content=document.getElementById('content');
editor.addEventListener('keypress',function(e){
addText(String.fromCharCode(e.which));
});
editor.addEventListener('keydown',function(e){
addText(String.fromCharCode(e.which));
});
function addText(words){
content.innerHTML=content.innerHTML+words;
}
#content{
width:500px;
height:auto;
}
#editor{
position:relative;
width:400px;
height:200px;
border:1px solid black;
word-wrap: break-word;
padding-left:4px;
padding-right:4px;
padding-bottom:1em;
box-sizing:border-box;
overflow:scroll;
}
<div id='editor' contenteditable='true' ></div>
<div id='content'></div>
您可以使用keyup功能来代替keypress和keydown