javascript - 防止默认输入键事件而不阻止滚动

标签 javascript dom scroll dom-events keydown

我想阻止除滚动之外的默认操作。当我在 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在这种情况下使用了contenteditableHere是 OP 的 JSFiddle 的一个分支。我在使不同的元素可编辑方面做了一些更改,因为这看起来更合适。

关于javascript - 防止默认输入键事件而不阻止滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094090/

相关文章:

javascript - 如何更新全局对象

javascript - 小数计数器 React + JS

javascript - 一个简单的语法奇迹 : access html object by their global name under IE?

jquery - 延迟加载整个 DIV 而不是单个图像

html - 如何让页面滚动到较长文本中的特定单词

html - 布局 : fixed text box on the left with scrollable MDL cards on the right

javascript - Meteoric:Meteor + Ionic 演示应用程序

JavaScript 对象结构 : how to access inner field with 'complex.key'

java - 在 java 中查询 xml 的最快方法

javascript - “dbclick”事件监听器不工作,但 'click' 正常