获得选定的文字和<pre> tag, where the offset is the start of the pre</pre>中的文字索引

时间:2011-11-18 19:41:02

标签: javascript jquery

所以我有一个像这样的预标签:

<pre> Some content, more content. <span>Coloured content</span>. Some more content</pre>

我想要做的是使用绑定mouseup事件的javascript或jquery设置事件。当用户选择文本时,我想让索引偏离pre的开头,因此它会忽略每个say的span标签。因此,如果有人在span标记之后选择了文本,它就知道要从预开口偏移。

有没有办法可以做到这一点?看起来像window.getSelection在span标记之后将其启动。

2 个答案:

答案 0 :(得分:2)

鉴于此HTML

<pre>0<span>1</span>23<span>4<span>56<span><span>7</span></span>8</span></span></pre>

你想得到第一个选定的数字作为输出/偏移,对吧? 基本思想是导航到DOM树中的左侧,直到没有更多节点具有相同的父节点。然后爬上去,最后到达pre标签。在通过树向左上方导航时,访问元素的所有字符都会被计算并添加到最终结果中。

$('pre').on('mouseup', function(){
    var selection = window.getSelection();
    // Get the offset within the container that holds all of the selection
    var offset = selection.anchorOffset;
    // A reference to the currently examined node
    var currentNode = selection.anchorNode;
    // Wander around until we hit the pre
    while(currentNode!==this){
        if(currentNode.previousSibling){
            // If there is a node left of us (with the same parent) navigate to the left and sum up the text length in the left node.
            // There is no need to check the children (possibly existent) since these would be included in text's return value
            offset = offset + $(currentNode.previousSibling).text().length;
            // Navigate to the left node of the current
            currentNode = currentNode.previousSibling;
        } else {
            // There is no left node so climb up towards the pre tag
            currentNode = currentNode.parentNode;
        }
    }
    // Print the final result
    console.log(offset);
});

脚本应输出所需的数字。因此,如果你选择78,你将获得7作为输出。

我只在Firefox中测试了这段代码。其他浏览器如果实现HTML Editing API也应该有效。 IE不支持until version 9。这同样适用于getSelection(请参阅MSDN)。

答案 1 :(得分:0)

这种事情变得非常复杂,尤其是当您需要担心跨浏览器实现时(*咳嗽* IE *咳嗽*)。因此,我强烈推荐Rangy,一个“跨浏览器JavaScript范围和选择库”。我自己用了一点,发现它完美无缺。

图书馆的作者Tim Down已经回答了很多关于范围和选择问题的问题,你会看到他们有多复杂:)