如何突出显示DOM Range对象的文本?

我使用鼠标在html页面(在firefox中打开)上选择一些文本,并使用javascript函数创建/获取与所选文本相对应的rangeobject。


 userSelection =window.getSelection(); 

 var rangeObject = getRangeObject(userSelection);

现在我要突出显示rangeobject下的所有文本。


  var span = document.createElement("span");

  rangeObject.surroundContents(span);

  span.style.backgroundColor = "yellow";

好吧,这仅在rangeobject(起点和终点)位于同一textnode时才有效,然后突出显示相应的文本。


    <p>In this case,the text selected will be highlighted properly,

       because the selected text lies under a single textnode</p>

但是,如果range对象覆盖多个文本节点,则它不能正常工作,它仅突出显示第一个textnode中的文本,例如


 <p><h3>In this case</h3>, only the text inside the header(h3) 

  will be highlighted, not any text outside the header</p> 

我不知道如何确定范围对象下的所有文本,突出显示范围范围是单个节点还是多个节点?谢谢....


潇湘沐
浏览 365回答 3
3回答

12345678_0001

Rangy是一个跨浏览器范围和选择库,可通过其CSS Class Applier模块完美解决此问题。我正在使用它在各种桌面浏览器和iPad上实现突出显示,并且效果很好。Tim Down的答案很好,但是Rangy让您不必自己编写和维护所有功能检测代码。

ibeautiful

您可以尝试为周围范围添加一个类并应用分层CSS吗?var span = document.createElement("span");span.className="selection";rangeObject.surroundContents(span);在CSS定义中,span.selection, span.selection * {&nbsp; &nbsp;background-color : yellow;&nbsp;&nbsp;}我没有尝试。但是只是猜测它会起作用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript