获取 contenteditable div 中的光标位置

发布于 2024-10-06 11:42:30 字数 922 浏览 0 评论 0原文

我在 SO 上找到了以下代码来获取 contenteditable div 的光标位置,但它总是返回 0。

应该检索位置的函数:

new function($) {
    $.fn.getCursorPosition = function() {
        var pos = 0;
        var input = $(this).get(0);
        // IE Support
        if (document.selection) {
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            pos = sel.text.length - selLen;
        }
        // Firefox support
        else if (input.selectionStart || input.selectionStart == '0')
            pos = input.selectionStart;

        return pos;
    }
} (jQuery);

我用来测试它的代码:

$('div.MESSAGE_OF_DAY').keyup(function() {
  alert($(this).getCursorPosition()); // always returns 0???
});

我正在使用 Chrome (8.0.1)。 552.215)如果重要的话。

I found the following code here on SO to get the position of the cursor of a contenteditable div, however it always returns 0.

The function that should retrieve the position:

new function($) {
    $.fn.getCursorPosition = function() {
        var pos = 0;
        var input = $(this).get(0);
        // IE Support
        if (document.selection) {
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            pos = sel.text.length - selLen;
        }
        // Firefox support
        else if (input.selectionStart || input.selectionStart == '0')
            pos = input.selectionStart;

        return pos;
    }
} (jQuery);

The code I use to test it:

$('div.MESSAGE_OF_DAY').keyup(function() {
  alert($(this).getCursorPosition()); // always returns 0???
});

I'm using Chrome (8.0.552.215) if it matters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零度℉ 2024-10-13 11:42:30

您找到的函数用于在输入或文本区域中查找插入符号或选择,而不是可内容编辑的元素。可以使用浏览器的 Selection< 根据 DOM 节点和该节点内的偏移量来获取插入符/选择边界位置/code>对象来获取 Range。我建议阅读有关这些对象的内容(我提供的链接是一个很好的起点)。在 Internet Explorer 中,此过程完全不同,但您可以使用我的 Rangy 库来消除差异。

The function you found is for finding the caret or selection in an input or textarea, not a contenteditable element. The caret/selection boundary position can be obtained in terms of a DOM node and offset within that node using the browser's Selection object to obtain a Range. I suggest reading about these objects (the links I've provided are a good starting point). In Internet Explorer, this process is completely different but you can use my Rangy library to eliminate the differences.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文