问题
I found this javascript code to highlight selected text, how can i add a function to delete the highlight background (deleting the span that was created) just clicking the highlighted text?
highlight=function()
{
var selection= window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span= document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selectedText);
selection.insertNode(span);
}
回答1:
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);
}
See demo
来源:https://stackoverflow.com/questions/8697188/this-function-highlight-selected-text-how-can-i-delete-the-span-made-by-javascr