在包含HTML内容的contentEditable区域中获取插入符号(光标)位置 [英] Get caret (cursor) position in contentEditable area containing HTML content

查看:306
本文介绍了在包含HTML内容的contentEditable区域中获取插入符号(光标)位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有contentEditable元素(可以是p,div,...),我想在其中得到插入符号(光标)。我通常可以用这段代码实现它:

I have contentEditable element (can be p, div, ...) and I would like to get caret (cursor) position in it. I can normally achieve it with this piece of code:

var position = window.getSelection().getRangeAt(0).startOffset;

这个元素只包含文本时工作正常。但是当元素包含一些HTML格式时,返回的位置相对于包含的HTML元素中的插入位置。

This works fine while the element contains just text. But when the element contains some HTML formatting, the returned position is relative to caret position within included HTML element.

让我们假设contentEditable元素的内容是这样的:

Let's assume contents of contentEditable element is this:

AB<b>CD</b>EF

如果插入符号在< b>< / b> 内,让我们说在C和D之间,上面代码的返回位置是1而不是3(从contentEditable元素的内容开始计算)

If caret is inside <b></b>, let's say between C and D, the returned position with above code is 1 instead of 3 (counted from the begining of the contentEditable element's content)

任何人都可以提出解决方案吗?

Can anybody come up with solution to this ?

推荐答案

更新



我写了一个更简单的版本,也适用于IE< 9:

UPDATE

I've written a simpler version of this that also works in IE < 9:

https://stackoverflow.com/a/4812022/96100

这实际上是一个比文本中的字符偏移更有用的结果整个文档:DOM范围的 startOffset 属性(这是 window.getSelection()。getRangeAt() returns)是相对于其 startContainer 属性的偏移量(顺便说一下,它不一定总是文本节点)。但是,如果你真的想要一个字符偏移,这里有一个函数可以做到。

This is actually a more useful result than a character offset within the text of the whole document: the startOffset property of a DOM Range (which is what window.getSelection().getRangeAt() returns) is an offset relative to its startContainer property (which isn't necessarily always a text node, by the way). However, if you really want a character offset, here's a function that will do it.

这是一个实例: http://jsfiddle.net/timdown/2YcaX/

这是函数:

function getCharacterOffsetWithin(range, node) {
    var treeWalker = document.createTreeWalker(
        node,
        NodeFilter.SHOW_TEXT,
        function(node) {
            var nodeRange = document.createRange();
            nodeRange.selectNode(node);
            return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
                NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
        },
        false
    );

    var charCount = 0;
    while (treeWalker.nextNode()) {
        charCount += treeWalker.currentNode.length;
    }
    if (range.startContainer.nodeType == 3) {
        charCount += range.startOffset;
    }
    return charCount;
}

这篇关于在包含HTML内容的contentEditable区域中获取插入符号(光标)位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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