window.getSelection()与HTML标签的偏移量?

如果我有以下HTML:

Vivamus luctus urna sed urna ultricies ac tempor dui sagittis.

我在mouseup上运行一个事件,它可以看到所选文本的范围:

 $(".content").on("mouseup", function () { var start = window.getSelection().baseOffset; var end = window.getSelection().focusOffset; if (start < end) { var start = window.getSelection().baseOffset; var end = window.getSelection().focusOffset; } else { var start = window.getSelection().focusOffset; var end = window.getSelection().baseOffset; } console.log(window.getSelection()); console.log(start + ", " + end); }); 

我从内容中选择Vivamus这个词,它会记录1, 8 ,因为这是选择的范围。

但是, 如果我选择单词urna ,它将记录urna ,但不会考虑HTML的元素。

无论如何, focusOffsetbaseOffset还要计算HTML标签,而不仅仅是文本?

更新

实例: http : //jsfiddle.net/FLwxj/61/

使用clearSelection()函数和替换方法 ,我能够实现所需的结果。

 var txt = $('#Text').html(); $('#Text').html( txt.replace(/<\/span>(?:\s)*/g, '') ); clearSelection(); 

资料来源:

  • clearSelection() : https : //stackoverflow.com/a/6562764/1085891
  • 替换方法: https : //stackoverflow.com/a/7168142/1085891

您可以在下面找到解决问题的方法。 我把它们放在代码效率的顺序。

工作方案

  • https://stackoverflow.com/a/8697302/1085891 ( 实例 )

     window.highlight = function() { var selection = window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span = document.createElement("span"); span.style.backgroundColor = "yellow"; span.appendChild(selectedText); span.onclick = function (ev) { this.parentNode.insertBefore( document.createTextNode(this.innerHTML), this ); this.parentNode.removeChild(this); } selection.insertNode(span); } 
  • https://stackoverflow.com/a/1623974/1085891 ( 实例 )

     $(".content").on("mouseup", function () { makeEditableAndHighlight('yellow'); }); function makeEditableAndHighlight(colour) { sel = window.getSelection(); if (sel.rangeCount && sel.getRangeAt) { range = sel.getRangeAt(0); } document.designMode = "on"; if (range) { sel.removeAllRanges(); sel.addRange(range); } // Use HiliteColor since some browsers apply BackColor to the whole block if (!document.execCommand("HiliteColor", false, colour)) { document.execCommand("BackColor", false, colour); } document.designMode = "off"; } function highlight(colour) { var range, sel; if (window.getSelection) { // IE9 and non-IE try { if (!document.execCommand("BackColor", false, colour)) { makeEditableAndHighlight(colour); } } catch (ex) { makeEditableAndHighlight(colour) } } else if (document.selection && document.selection.createRange) { // IE <= 8 case range = document.selection.createRange(); range.execCommand("BackColor", false, colour); } } 
  • https://stackoverflow.com/a/12823606/1085891 ( 实例 )

其他有用的方案: