检测 jQuery 中的“输入内的光标位置何时更改”

Detect when "cursor position inside input change" in jQuery?

本文关键字:位置 光标 何时更 jQuery 中的 输入 检测      更新时间:2023-09-26

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

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

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

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

不,没有像"光标位置已更改"这样的事件。

但是,如果您想知道光标位置是否更改,则可以执行以下操作:用jQuery 1.7测试,我在Ie8和chrome中测试过

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

控制台.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;
}

我自己需要这样的东西,所以基于@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');

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

在纯 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()
  }
}

在 React 中,我们可以为输入标签添加一个 onSelect 事件处理程序。在JS中,它将是onSelectstart https://learn.javascript.ru/selection-range#sobytiya-pri-vydelenii。