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

时间:2012-02-25 19:50:16

标签: javascript

例如,如果我有一个网页HTML,如下所示

<body>
        Hello Techies, <br>
        Techies here.
</body>  

如果我使用

搜索“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(); 
 }

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

1 个答案:

答案 0 :(得分:7)

尝试使用while循环:

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