问题
When a user selects any text in my html page I want to add a custom style (like color:red;
) to it. This will act as a highlighting tool similar to what you can see in some applications for reading pdf files.
To do this I declare highlight()
function that gets the text which is selected, plus its position.
function highlight(text, x, y) {
alert(text+'***'+x+'***'+y)
window.getSelection().removeAllRanges();
}
jsfiddle link edited
jsFiddle
回答1:
Try this approach instead. Basic steps are get your selection, pass it into the getRangeAt method and then create a new span element to surround the selection and apply your class attribute.
$(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
回答2:
After some research i suggest to go this way.
html
<h3 class="foo">hello world! hello world! hello world</h3>
<div class="foo">hello world! hello world hello world!</div>
<span class="foo">hello world! hello world</span>
css
.foo::selection {
color:#ff0099;
}
.bar::selection {
color: red;
}
js
$(document).ready(function(){
$(".foo").removeClass("foo").addClass("bar");
});
fiddle
First add a class
in your element you want to use the effect. After use selection selector and with js
add
and remove
the classes
. Hope that helps :)
来源:https://stackoverflow.com/questions/24342007/highlight-selected-text-with-jquery