我想阻止除滚动之外的默认操作。当我在 keyDown
事件(Enter 键)中添加 e.preventDefault
时,它也会阻止浏览器滚动。我想阻止除滚动之外的按回车键的操作。有没有办法区分回车键事件和滚动事件?或者我们可以部分阻止滚动应该起作用而其他操作被阻止的默认操作。任何帮助将不胜感激。
document.getElementById('textBox').addEventListener("keydown", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
}
});
我在输入操作中添加了 preventDefault
。由于某种原因,我必须将这一行添加到代码中,但这也会阻止我的页面滚动。
我想保留 preventDefault
但我的页面应该滚动。有什么办法可以做到吗?
最佳答案
每当触发事件时,只需向文本区域添加一个新行。
document.getElementById('textBox').addEventListener("keydown", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
var cursor= this.selectionEnd;
this.value = this.value.substring(0, cursor) + '\n' +
this.value.substring(cursor);
this.selectionEnd = cursor+1;
event.preventDefault();
}
});
<textarea style="height:200px;width:300px" id="textBox"></textarea>
注意:我注意到OP在这种情况下使用了contenteditable
。 Here是 OP 的 JSFiddle 的一个分支。我在使不同的元素可编辑方面做了一些更改,因为这看起来更合适。
关于javascript - 防止默认输入键事件而不阻止滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094090/