在移动设备上无法检测到输入(textarea)

时间:2016-02-24 09:50:27

标签: javascript google-chrome

要检测输入按我使用简单的解决方案:

if (e.keyCode == 13) {
    // do something
}

在桌面上,它可以在任何地方正常工作在平板电脑上,智能手机 - 也是 - 但是,如果它来到textarea这不起作用。

由于最近的Chrome更新很少,因此成为一个问题。

因此,当您从移动设备按Enter键时,您只会看到新行“\ n”,但没有执行任何功能。

那么,如何在最新的chrome版本上检测移动设备上的textarea输入?

2 个答案:

答案 0 :(得分:1)

虽然它可能是特定于Chrome的错误,但可能是某些可能的解决方案:

  1. 同时检查e.which

    var key = e.which || e.keyCode || 0;
    if (key == 13) {
        // do something
    }
    
  2. 尝试其他活动:例如如果您正在使用keyUp,请尝试keyPress

  3. 如果仍然无法正常工作,则可能需要一种解决方法,如果检测很重要。您可以跟踪该值并检测一次" \ n"使用input事件添加到textarea。

    var textarea = document.getElementById('your-textarea');
    var textareaValue = textarea.value;
    var textareaLines = getLines(textareaValue);
    
    function getLines(str) {
        // This uses RegEx to match new lines.
        // We use || [] because it would otherwise fail if there weren't
        // any line breaks yet.
    
        return (str.match(/[\n\r]/g) || []).length;
    }
    
    textarea.addEventListener('input', function() {
        var newValue = textarea.value;
        var newLines = getLines(newValue);
    
        if (newLines > textareaLines
            && newValue.length == textareaValue.length + 1) {
    
            // We also check that the new length is only one
            // character longer to not fire this new line event
            // after a copy-paste with a new line character.
    
            doSomething();
        }
    
        textareaValue = newValue;
        textareaLines = newLines;
    }, false);
    

答案 1 :(得分:1)

如果你像我一样使用 React,onKeyPress={e => e.key} 可以工作。

e.key 在浏览器和移动设备上返回“Enter”

e.code 仅在浏览器上返回“Enter”

相关问题