2016-12-31 1 views
1
<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

이미 강조 표시된 클래스가있는 요소가 있는지 확인해야합니다. 그렇다면 먼저 content div 요소 내에서 강조 표시된 모든 범위를 제거하십시오.

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>

관련 문제