在其他文本中搜索文本并使用javascript突出显示

2 javascript

在html静态页面的buttonclick上找到文本框中给定的文本.然后使用javascript高亮显示它

Jos*_*lio 5

这是一个在页面中搜索文本的代码示例.它基本上相当于在浏览器中执行Find with CTRL+ Fin.如果您使用jQuery库,则可以使用Search-Highlight插件以与Google搜索类似的方式突出显示文本.

<html>
<head>
<script language="JavaScript">
<!--
var TRange=null;
function findString (str) {
 if (parseInt(navigator.appVersion)<4) return;
 var strFound;
 if (window.find) {

  // CODE FOR BROWSERS THAT SUPPORT window.find
  strFound=self.find(str);
  if (strFound && self.getSelection && !self.getSelection().anchorNode) {
   strFound=self.find(str)
  }
  if (!strFound) {
   strFound=self.find(str,0,1)
   while (self.find(str,0,1)) continue
  }
 }
 else if (navigator.appName.indexOf("Microsoft")!=-1) {

  // EXPLORER-SPECIFIC CODE

  if (TRange!=null) {
   TRange.collapse(false)
   strFound=TRange.findText(str)
   if (strFound) TRange.select()
  }
  if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange()
   strFound=TRange.findText(str)
   if (strFound) TRange.select()
  }
 }
 else if (navigator.appName=="Opera") {
  alert ("Opera browsers not supported, sorry...")
  return;
 }
 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}
//-->
</script>
</head>
<body>
<form name="f1" action="" 
    onSubmit="if(this.t1.value!=null && this.t1.value!='') findString(this.t1.value);return false">
    <input type="text" name=t1 value="" size=20>
    <input type="submit" name=b1 value="Find">
    <p>This is some sample text.</p>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)