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

时间:2013-11-03 17:14:22

标签: javascript jquery input

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

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

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

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

3 个答案:

答案 0 :(得分:17)

不,没有“光标位置已更改”等事件。

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

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

如果光标已更改,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;
}

答案 1 :(得分:0)

我自己也需要类似的东西,因此基于@RenatoPrado解决方案,我创建了一个jQuery扩展(位于npm-jquery-position-event上)。

要使用它,您可以添加标准事件:

var textarea = $('textarea').on('position', function(e) {
   console.log(e.position);
});

,如果需要初始值,可以使用:

var textarea = $('textarea').on('position', function(e) {
   console.log(e.position);
}).trigger('position');

该事件还具有有用的列和行属性。

答案 2 :(得分:0)

纯 JS 中,还记得插入位置,如果有遗漏的事件请告诉我。

const textarea = document.querySelector('textarea')

const storeCaretPos = () =>
  requestAnimationFrame(() =>
    localStorage.setItem('caretPos', textarea.selectionStart),
  )

textarea.oninput = textarea.onclick = textarea.oncontextmenu = storeCaretPos

textarea.onkeyup = ({ key }) => {
  if (['Arrow', 'Page', 'Home', 'End'].some(type => key.startsWith(type))) {
    storeCaretPos()
  }
}
相关问题