gpt4 book ai didi

javascript - 无法检测到手机上的输入键(文本区域)

转载 作者:搜寻专家 更新时间:2023-11-01 04:35:46 25 4
gpt4 key购买 nike

为了检测回车,我使用了简单的解决方案:

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

在桌面上它可以在任何地方正常工作。在平板电脑和智能手机上 - 也是 - 但是,如果涉及到文本区域,这将不起作用。

由于上次 chrome 更新很少,这成了一个问题。

因此,当您在移动设备上按回车键时,您只会看到新行“\n”,但不会执行任何函数。

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

最佳答案

虽然这可能是 Chrome 特定的错误,但这些可能是一些可能的解决方案:

  1. 同时检查 e.which:

    var key = e.which || e.keyCode || 0;
    if (key == 13) {
    // do something
    }
  2. 尝试不同的事件:例如如果您使用的是 keyUp,请尝试 keyPress


如果这仍然不起作用,如果检测很重要,您可能需要一个解决方法。您可以使用 input 事件跟踪该值并检测“\n”是否被添加到文本区域。

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);

关于javascript - 无法检测到手机上的输入键(文本区域),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com