使用jquery突出显示所选文本

当用户选择我的html页面中的任何文本时,我想向其添加自定义样式(如color:red; )。 这将作为突出显示工具,类似于您在某些应用程序中可以看到的用于读取pdf文件的突出显示工具。

为此,我声明了highlight()函数,它获取所选文本及其位置。

 function highlight(text, x, y) { alert(text+'***'+x+'***'+y) window.getSelection().removeAllRanges(); } 

jsfiddle链接已编辑

的jsfiddle

请尝试这种方法。 基本步骤是获取您的选择,将其传递到getRangeAt方法,然后创建一个新的span元素以包围选择并应用您的类属性。

 $(document).on("mouseup", function (e) { var selected = getSelection(); var range = selected.getRangeAt(0); if(selected.toString().length > 1){ var newNode = document.createElement("span"); newNode.setAttribute("class", "red"); range.surroundContents(newNode); } selected.removeAllRanges(); }); function getSelection() { var seltxt = ''; if (window.getSelection) { seltxt = window.getSelection(); } else if (document.getSelection) { seltxt = document.getSelection(); } else if (document.selection) { seltxt = document.selection.createRange().text; } else return; return seltxt; } 

DEMO

经过一些研究,我建议采取这种方式。

HTML

 

hello world! hello world! hello world

hello world! hello world hello world!
hello world! hello world

CSS

 .foo::selection { color:#ff0099; } .bar::selection { color: red; } 

JS

 $(document).ready(function(){ $(".foo").removeClass("foo").addClass("bar"); }); 

小提琴

首先在要使用效果的元素中添加一个class 。 使用选择选择器后,使用js addremove classes 。 希望有所帮助:)