Javascript 获取所选文本&;a<;预处理>;标记,其中偏移量是预处理的起点
我有一个这样的预标记:Javascript 获取所选文本&;a<;预处理>;标记,其中偏移量是预处理的起点,javascript,jquery,Javascript,Jquery,我有一个这样的预标记: <pre> Some content, more content. <span>Coloured content</span>. Some more content</pre> $('pre').on('mouseup', function(){ var selection = window.getSelection(); // Get the offset within the container tha
<pre> Some content, more content. <span>Coloured content</span>. Some more content</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);
});
一些内容,更多内容。彩色内容。更多内容
我想做的是使用javascript或jquery设置一个绑定mouseup事件的事件。当用户选择文本时,我希望从pre的开始处获得索引偏移量,因此它会忽略span标记。因此,如果有人选择span标记后的文本,它知道从预打开偏移
我有办法做到这一点吗?看起来window.getSelection会在span标记之后启动它。这种事情变得非常复杂,特别是当您需要担心跨浏览器实现(*cough*IE*cough*)时。因此,我强烈推荐一个“跨浏览器JavaScript范围和选择库”。我自己也使用过它,发现它工作得非常好 图书馆的作者,已经回答了很多关于范围和选择问题的问题,你会看到它们变得多么复杂:)鉴于这个HTML 脚本应输出所需的数字。所以如果你选择78,你会得到7作为输出
我只在Firefox中测试了这段代码。如果其他浏览器能够实现,那么它们也应该可以工作。IE不支持它。这同样适用于
getSelection
(请参阅)。我并不担心IE 9的不足。这是一个内部工具,大约有六个人在使用它,我们都不使用IE,因为我们都知道得更多;)。我会检查这个,如果我有任何问题,请告诉你,谢谢你的回复。
$('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);
});