代码收藏 JS实现页内查找定位功能

前部分为IE下搜索方法 用TextRange来实现

后部分为firefox、chrome下搜索方法

 1         var nextIndex = 0;
 2         var searchValue = '';
 3         var input1=document.getElementById('input1');
 4 
 5         function findInPage(searchText) {
 6             if (!searchText){
 7                 alert('搜索字符串为空');
 8             }
 9 
10             if(searchText && searchText != searchValue && nextIndex > 0){
11                 searchValue = searchText;
12                 nextIndex = 0;
13             }else{
14                 searchValue = searchText;
15             }
16 
17             if (document.all) {
18                 txt = document.body.createTextRange();
19                 var found =false;
20                 for (var i = 0; i <= nextIndex && (found = txt.findText(searchValue))==true; i++) {
21                     txt.moveStart("character", 1);
22                     txt.moveEnd("textedit");
23                 }
24 
25                 if (found) {
26                     txt.moveStart("character",-1);
27                     txt.findText(searchValue);
28                     txt.select();
29                     txt.scrollIntoView();
30                     nextIndex++;
31                 }else{
32                     if (nextIndex > 0) {
33                         nextIndex = 0;
34                         findInPage(searchValue);
35                     }
36                 }
37             }else{
38                 window.find(searchValue,false,true);
39             }
40         }    
原文地址:https://www.cnblogs.com/verlen11/p/4466861.html