作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
为了检测回车,我使用了简单的解决方案:
if (e.keyCode == 13) {
// do something
}
在桌面上它可以在任何地方正常工作。在平板电脑和智能手机上 - 也是 - 但是,如果涉及到文本区域,这将不起作用。
由于上次 chrome 更新很少,这成了一个问题。
因此,当您在移动设备上按回车键时,您只会看到新行“\n”,但不会执行任何函数。
那么,如何在最新的 chrome 版本上检测移动设备上文本区域的输入?
最佳答案
虽然这可能是 Chrome 特定的错误,但这些可能是一些可能的解决方案:
同时检查 e.which
:
var key = e.which || e.keyCode || 0;
if (key == 13) {
// do something
}
尝试不同的事件:例如如果您使用的是 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/
我是一名优秀的程序员,十分优秀!