2016-12-31 13 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

すでに強調表示されているクラスを持つ要素があるかどうかを確認する必要があります。はいの場合は、最初にコンテンツ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>

関連する問題