使用window.find()匹配所有匹配项

Exc*_*ion 5 javascript

例如,如果我有一个像下面这样的网页HTML

<body>
        Hello Techies, <br>
        Techies here.
</body>  
Run Code Online (Sandbox Code Playgroud)

如果我使用搜索"Techies"

 var sel = window.getSelection(); 
 sel.collapse(document.body, 0); 
 document.body.offsetHeight;
 if (window.find("Techies", true)) { 
   document.execCommand("hiliteColor", false, "YellowGreen"); 
   sel.collapseToEnd(); 
 }
Run Code Online (Sandbox Code Playgroud)

它突出了"Techies"的第一次发生.但是当我用Ctrl + F搜索时,第一次出现将在黑暗中突出显示,下一次出现将以浅色模式突出显示.如何使用上面的代码实现相同的功能.

rai*_*7ow 8

尝试使用while循环:

if (window.find("Techies", true)) { 
   document.execCommand("hiliteColor", false, "FirstColor");
   while (window.find("Techies", true)) {
      document.execCommand("hiliteColor", false, "SecondColor");
   }
   ...
}
Run Code Online (Sandbox Code Playgroud)