[英]Javascript : How to get the last two characters typed into a textarea?
[英]How to get the position of a typed letter in a textarea with Javascript?
我在输入文本区域时创建了一个下拉列表。 给定键盘输入事件,如何获得键入字母的位置?
var oldValue = '';
var keyup = function() {
var value = document.getElementById('myTextArea').value;
for(var i=0; i<value.length; i++) {
if(i >= oldValue.length) {
// letter typed at end
oldValue = value;
return; // not really necessary since we should be at the end of the loop anyway
} else if(value.charAt(i) !== oldValue.charAt(i)) {
// letter typed at i
oldValue = value;
return; // no need to keep searching
}
}
// no new letters typed
}
格雷格的答案似乎奏效。 但是,如果您想要更简单的方法来获取它,则可以访问textarea的selectionStart
属性。
例如
var myTextArea = $("#mytextarea");
myTextArea.keyup(function () {
console.log("The last typed character is at: ", myTextArea.get(0).selectionStart - 1);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.