获取插入符号位置的常见解决方案会返回奇怪的结果

Common solution to get caret position returns weird results

本文关键字:返回 结果 常见 插入 符号 位置 获取 解决方案      更新时间:2023-09-26

我正在尝试获取文本区域中的插入符号位置。我使用了很多不同的方法,其中大多数都涉及到获取范围或获取元素的selectionStart。出于某种原因,虽然它在某种程度上起作用,但每当我仍在键入新字符并且还没有插入任何字符时,它都会比应该的少返回一个字符。

例如:给定以下输入,插入符号为|:

|      : 0
a|     : 1
ab|    : 1 <- weird!
abc|   : 2 <- still weird
ab|    : 2 <- back to normal
abc|   : 2 <- back to weird
ad|bc  : 2 <- normal 
adbce| : 5 <- now normal

我想我不确定什么时候会发生——如果你输入了一些字符,但没有插入字符串的中间,然后它又开始工作,那么它似乎少了一个。

为什么第二个字符不添加到插入符号位置?其他人找到这个了吗?

编辑:它在"输入"事件上运行:

// use a solution from stack that works with jquery:
(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).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;
    }
})(jQuery);
$(window).load(function(){
    // when editing the query box
    $("#query_textarea").bind('input', function(){
         window.status=$("#query_textarea").getCaretPosition();
         // do some other stuff
    }
}

我在Mac 上运行Chrome

我在使用旧的基于webkit的浏览器为嵌入式设备开发时遇到了同样的问题。这是调度事件和更新控件的时间问题。在事件处理程序中,我检查字段值的长度和插入符号的位置,当在字段中键入时,它们不相同。据我所知,该问题已于2013年年中在webkit中得到解决。参考编号:https://bugs.webkit.org/show_bug.cgi?id=110742

Edge、最近的Safari、Firefox、Chrome都能正常工作。

这能回答您的问题吗?

纯JS:https://stackoverflow.com/a/1891501/671373

jQuery:https://stackoverflow.com/a/1909997/671373

否则,您可能会选中"jQuery-fieldSelection"
https://github.com/localhost/jquery-fieldselection
从其描述来看:"一个jQuery插件,用于获取'设置插入符号/选择。"