this function highlight selected text, how can i delete the span made by javascript clicking the highlighted text?

感情迁移 提交于 2019-12-24 10:17:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!