本文分享一個以 JavaScript 實作網頁字元定位的做法:輸入要查詢的字串,點擊定位後程式會自動跳到第一個符合的位置,供大家參考。
<html>
<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">
</form>
<p>這裡是要搜尋的段落文字,程式會在頁面中尋找並定位到你輸入的字串。</p>
<script language="JavaScript">
<!--
var TRange=null;
function findString (str) {
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (window.find) {
// 支援 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) {
// IE 專用程式碼
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>
</html>這個範例針對不同瀏覽器分別採用 window.find 與 IE 的 TextRange 來實作字串定位,輸入關鍵字後即可自動跳轉並選取符合的文字。