简体   繁体   English

如何使用Javascript在文本区域中获取键入字母的位置?

[英]How to get the position of a typed letter in a textarea with Javascript?

I am creating a dropdown while typing in a textarea. 我在输入文本区域时创建了一个下拉列表。 How can I get the position of the typed letter given a keyup event? 给定键盘输入事件,如何获得键入字母的位置?

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
}

Greg's answer seems to work. 格雷格的答案似乎奏效。 But if you want a more simpler way to get it, you can access the selectionStart property of the textarea. 但是,如果您想要更简单的方法来获取它,则可以访问textarea的selectionStart属性。

For example 例如

var myTextArea = $("#mytextarea");

myTextArea.keyup(function () {

   console.log("The last typed character is at: ", myTextArea.get(0).selectionStart - 1);

});

http://jsfiddle.net/wasjdhtu/ http://jsfiddle.net/wasjdhtu/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM