Javascript 如何在textarea上捕获输入键而不是shift + enter?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6178431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:35:25  来源:igfitidea点击:

How to catch enter keypress on textarea but not shift+enter?

javascriptjavascript-events

提问by rsk82

I'm doing it for texarea. A function should be called when the user press Enter, but nothing should be done when Shift+ Enterbe pressed.

我正在为 texarea 做这件事。当用户按下时应该调用一个函数Enter,但按下Shift+时什么都不做Enter

I try to simulate here a feature that many IM communicators have: sending a message on Enterbut also adding multiple lines using Shift+ Enter.

我尝试在这里模拟许多 IM 通信器具有的功能:发送消息Enter但也使用Shift+添加多行Enter

回答by aorcsik

Test for the enter keycode (13) and if shift key was pressed.

测试输入键码 (13) 以及是否按下了 shift 键。

...onkeyup = function(e) {
    if (e.keyCode == 13)
    {
//      if (e.shiftKey === true)
        if (e.shiftKey)  // thruthy
        {
            // new line
        }
        else
        {
            // run your function
        }
        return false;
    }
}

Edit:Accept all truthy values of e.shiftKey

编辑:接受所有真实值e.shiftKey

回答by ic3b3rg

element.onkeydown = function(o) {
  o = o || event;
  if (o.shiftKey && o.keyCode == 13) {
    /* shift + enter pressed */
  }
}

回答by nickytonline

I believe you need a keydown event as well to check for the SHIFT key, http://www.quirksmode.org/js/keys.html

我相信您还需要一个 keydown 事件来检查 SHIFT 键,http://www.quirksmode.org/js/keys.html

回答by ADW

Look at the shiftKey property of the event object which will tell you if shift was held while the key was pressed.

查看事件对象的 shiftKey 属性,它会告诉您按下键时是否按住了 shift。