Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        2年前关闭。
                                                                                            
                
        
<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);
    }
}
}


大家好,我在这里遇到了问题。再次按下“查找”按钮后,如何删除突出显示的单词?

最佳答案

您需要检查是否已经有一个具有突出显示的类的元素。如果是,则首先删除content 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>

关于javascript - 如何删除突出显示的单词? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41407918/

10-11 05:43