此功能突出显示选定的文本,我如何删除由javascript单击突出显示的文本所做的跨度? [英] this function highlight selected text, how can i delete the span made by javascript clicking the highlighted text?

查看:74
本文介绍了此功能突出显示选定的文本,我如何删除由javascript单击突出显示的文本所做的跨度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现此JavaScript代码以突出显示选定文本,如何添加删除突出显示背景的功能(删除创建的范围),然后单击突出显示的文本?

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);
    }


推荐答案

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);
}

这篇关于此功能突出显示选定的文本,我如何删除由javascript单击突出显示的文本所做的跨度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆