在jQuery中检测"输入中的光标位置变化"?

Pal*_*ini 15 javascript jquery input

我正在使用一个名为jQuery TextRange的插件来获取光标在输入中的位置(在我的例子中,是一个textarea)并设置位置.

但现在我有一件事 - 我认为 - 更难解决.我想知道在jQuery中是否存在一个像"光标位置已更改"的事件.我的意思是:

$('#my-input').on('cursorchanged', function(e){
    // My code goes here.
)};
Run Code Online (Sandbox Code Playgroud)

我想知道光标在输入/文本区域内移动的时间,无论是通过箭头键还是鼠标单击都无关紧要.我是一个jQuery新手,但我认为在jQuery上不存在这样的事件,或者存在?

Ren*_*ado 19

不,没有像"光标位置改变"这样的事件.

但是如果你想知道光标位置是否改变了,你可以这样做:用jquery 1.7测试,我在Ie8和chrome中测试过

var last_position = 0;
$(document.ready(function () {
    $("#my_input").bind("keydown click focus", function() {
        console.log(cursor_changed(this));
    });
});
Run Code Online (Sandbox Code Playgroud)

如果光标已更改,则console.log将返回

function cursor_changed(element) {
    var new_position = getCursorPosition(element);
    if (new_position !== last_position) {
        last_position = new_position;
        return true;
    }
        return false;
}

function getCursorPosition(element) {
    var el = $(element).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    return pos;
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要使用`keyup`而不是`keydown`,否则回调将在键事件之后选择先前的插入位置而不是下一个插入位置. (9认同)
  • 当它们由上下文菜单操作(剪切/粘贴/撤消/删除)引起时,它似乎没有注意到光标位置的变化。 (2认同)
  • @罗伯特,好点。这可以通过观察另一个事件 - “input” 事件来解决(请参阅 [Mozilla 文档](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event))。 (2认同)