在contenteditable div中获取光标位置 [英] Get cursor-position in contenteditable div

查看:1599
本文介绍了在contenteditable div中获取光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SO上找到了以下代码来获取内容可编辑div的光标的位置,但是它始终返回0.

I found the following code here on SO to get the position of the cursor of a contenteditable div, however it always returns 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.552.215).

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

推荐答案

您发现的功能是在输入或文本区域中找到插入符号或选择内容,而不是可编辑的元素.使用浏览器的 Selection 对象以获得 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.

这篇关于在contenteditable div中获取光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆