所以我有一个像这样的预标记:
<pre> Some content, more content. <span>Coloured content</span>. Some more content</pre>
我想做的是使用javascript或jquery来设置一个绑定mouseup事件的事件。当用户选择文本时,我想从pre的开头获得索引偏移量,所以它会忽略span标记。因此,如果有人选择了span标记之后的文本,它就知道要从预打开位置偏移。
有什么办法我能做到这一点吗?它看起来像window.getSelection在span标记之后启动它。
给定此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编辑API,它们也应该可以工作。IE直到版本9才支持它。这同样适用于getSelection
(请参阅MSDN(。
这类事情会变得非常复杂,尤其是当您需要担心跨浏览器实现(*cuck*IE*cuck*(时。因此,我强烈推荐Rangy,一个"跨浏览器JavaScript范围和选择库"。我自己也用过一点,发现它非常完美。
图书馆的作者Tim Down在SO上回答了很多关于范围和选择问题的问题,你会看到它们有多复杂:(