我试图在文章中为选择的开始和结束获得字符偏移量.但是,我想在这个过程中忽略一些元素.
在我的应用程序中,服务器正在使用HTML之前JS动态注入一些元素,并且文本中的字符数在服务器和客户端之间保持一致非常重要.
我希望它会像window.getSelection()
一起一样简单user-select: none;
.遗憾的是,尽管文本看起来没有被选中,但它仍然包含在选择范围内.
我在下面写了一个简短的例子.我曾经写过一篇removeFromSelection
没有太大成功的解决方法.也许我需要删除重叠的范围,.unselectable
并用全新的范围对象手动填补空白.我觉得这应该比我做的更容易.我应该怎么做?
function findAncestorOffset(container, node, offset)
{
if (node == container)
return offset;
var parent = node.parentNode;
var syblings = parent.childNodes;
for (var i = 0, len = syblings.length; i < len; i++)
{
if (syblings[i] == node)
break;
offset += $(syblings[i]).text().length;
}
return findAncestorOffset(container, parent, offset);
}
function removeFromSelection(selector, selection)
{
$(selector).each(function(i, node){
var range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges(range);
});
}
var onSelect = function(){
var sel = window.getSelection();
//removeFromSelection('.unselectable', sel);
var text = sel.toString();
$('#out').text(text);
var range = sel.getRangeAt(0).cloneRange();
var i = findAncestorOffset($('.article')[0], range.startContainer, range.startOffset);
$('#from').text(i);
$('#to').text(i + text.length);
}
$('.article').mouseup(onSelect);
$('.article').focusout(onSelect);
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
pre, .article {
border: solid 1px black;
padding: 12px;
}
Select This
This can be selected.
This can't.
And this can again.
Output
From: , To: