Range for Complex Selection
I want to highlight the user selected Text. I cant use the JQuery Based API for Highlight since I want user specific highlight.
Here is how my code looks like.
var range = window.getSelection().getRangeAt(0);
var sel = window.getSelection();
range.setStart( sel.anchorNode, sel.anchorOffset );
range.setEnd(sel.focusNode,sel.focusOffset);
highlightSpan = document.createElement("span");
highlightSpan.setAttribute("style","background-color: yellow; ");
highlightSpan.appendChild(range.extractContents());
range.insertNode(highlightSpan)
This works in normal scenarios but if I select some text in different paragraphs the extractContents API will validate the HTML 开发者_JS百科returned and put additional tags to make it valid HTML. I want the exact HTML that was selected without the additional validating that javascript did.
Is there any way this can be done?
Regards, Tina
This has come up a few times:
How can I highlight the text of the DOM Range object? Javascript Highlight Selected Range Button
Here's my answer:
The following should do what you want. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.
function highlight(colour) {
var range, sel;
if (window.getSelection) {
// Non-IE case
sel = window.getSelection();
if (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";
} else if (document.selection && document.selection.createRange) {
// IE case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
精彩评论