如何删除突出显示的单词?

时间:2016-12-31 11:30:30

标签: javascript jquery html css jsp

<input type="text" id="search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">

<div id="content">
<p>Hello World!</p>


function doSearch(text) {
if (window.find && window.getSelection) {
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.body, 0);

    while (window.find(text)) {
        document.execCommand("HiliteColor", false, "yellow");
        sel.collapseToEnd();
    }
    document.designMode = "off";
} else if (document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    while (textRange.findText(text)) {
        textRange.execCommand("BackColor", false, "yellow");
        textRange.collapse(false);
    }
}
}
嘿伙计们,我在这里面临一个问题。再次按下查找按钮后如何删除突出显示的单词?

1 个答案:

答案 0 :(得分:1)

您需要检查是否已有一个具有突出显示的类的元素。如果是,则首先删除内容div p元素内的所有突出显示的跨度。

 if(document.querySelector('span[style*="background-color: yellow;"]') !== null) {
        var elem = document.querySelector("#content p");
        var txt = elem.innerText || elem.textContent;
        elem.innerHTML = txt;
   }

function doSearch(text) {
  
   if(document.querySelector('span[style*="background-color: yellow;"]') !== null){
        var elem = document.querySelector("#content p");
        var txt = elem.innerText || elem.textContent;
        elem.innerHTML = txt;
   }
  
if (window.find && window.getSelection) {
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.body, 0);

    while (window.find(text)) {
        document.execCommand("HiliteColor", false, "yellow");
        sel.collapseToEnd();
    }
    document.designMode = "off";
} else if (document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    while (textRange.findText(text)) {
        textRange.execCommand("BackColor", false, "yellow");
        textRange.collapse(false);
    }
}
}
<input type="text" id="search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">

<div id="content">
<p>Hello World!</p>
</div>