本文示範如何在網頁上做出一個類似瀏覽器「尋找」功能的浮動視窗:使用者輸入關鍵字後,程式會在頁面中逐筆搜尋並選取文字,還能拖動視窗、關閉視窗。完整程式碼如下:
復制代碼 代碼如下:<html>
<head>
<title>JS+CSS模仿的網頁字符查找功能</title>
<style type=text/css>
BODY { FONT-SIZE:12px; LETTER-SPACING:1pt; line-height:22px; margin-left:5pt; margin-top:5pt }
#scontentmain { position:absolute; top:28px; width:228px; height:30px; }
#scontentbar { border:1px solid black; cursor:hand; height:15px; position:absolute; top:5px; width:100%; }
#scontentsub { position:absolute; top:28px; width:100%; }
TD { font-size:12px }
</style>
</head>
<body>
<br>中國<br>晉州<br>百戰疲勞壯士哀<br>洛<br>黃損<br>江淮<br>寶馬<br>誇張<br>美國<br>Ajax<br>ASP<br>JAVA<br>JQUERY
<SCRIPT language=JavaScript>
var dragapproved=false;
function drag_onclick() {
if (search1.drag.checked == true) dragapproved=false; else dragapproved=true;
}
function movescontentmain(){
if (event.button==1 && dragapproved && search1.drag.checked == true){
zcor.style.pixelLeft = tempvar1 + event.clientX - xcor;
zcor.style.pixelTop = tempvar2 + event.clientY - ycor;
return false;
}
}
function dragscontentmain(){
if (event.srcElement.id=="scontentbar"){ dragapproved=true; zcor=scontentmain; tempvar1=zcor.style.pixelLeft; tempvar2=zcor.style.pixelTop; xcor=event.clientX; ycor=event.clientY; document.onmousemove=movescontentmain; }
}
document.onmousedown=dragscontentmain;
document.onmouseup=new Function("dragapproved=false");
var win = this; var n = 0;
function findInPage(str) {
var txt, i, found;
if (str == "") return false;
if (document.all) {
txt = win.document.body.createTextRange();
for (i = 0; i <= n && (found = txt.findText(str)) != false; i++){ txt.moveStart("character", 1); txt.moveEnd("textedit"); }
if (found){ txt.moveStart("character", -1); txt.findText(str); txt.select(); txt.scrollIntoView(); n++; }
else { if (n > 0){ n = 0; findInPage(str); } else alert(str + " ... 您要找的文字不存在。"); }
}
return false;
}
</SCRIPT>
</body>
</html>
重點在於 findInPage:利用 IE 的 TextRange 物件反覆呼叫 findText 逐一比對並選取文字,找不到時提示使用者;而 dragscontentmain 與 movescontentmain 則讓浮動視窗能被滑鼠拖動。這是一個用到舊式 IE API 的經典小工具,很適合作為練習 DOM 操作的題材。