您的位置:首页 > Web前端 > JavaScript

JS屏幕搜索,实现CTRL + F的效果

2012-04-18 17:01 591 查看
JS code如下:

<script type="text/javascript">
var DOM = (document.getElementById) ? 1 : 0;
var NS4 = (document.layers) ? 1 : 0;
var IE4 = 0;
if (document.all) {
IE4 = 1;
DOM = 0
}
var win = window;
var n = 0;
function findIt() {
if (document.getElementById("searchstr").value != "")
findInPage(document.getElementById("searchstr").value)
}
function findInPage(str) {
var txt, i, found;
if (str == "") return false;
if (DOM) {
win.find(str, false, true);
return true
}
if (NS4) {
if (!win.find(str)) while (win.find(str, false, true)) n++;
else n++;
if (n == 0) alert("未找到指定内容.")
}
if (IE4) {
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("未找到指定内容.")
}
}
return false
}
</script>


调用代码如下:

<input type="text" id="searchstr" name="searchstr" style="width: 200px" />
<input type="button" value="屏幕查找" onclick="javascript:findIt();" />


完整的网页Demo程序:

<html>
<head>
<title>Untitled Page</title>
<script type="text/javascript"> var DOM = (document.getElementById) ? 1 : 0; var NS4 = (document.layers) ? 1 : 0; var IE4 = 0; if (document.all) { IE4 = 1; DOM = 0 } var win = window; var n = 0; function findIt() { if (document.getElementById("searchstr").value != "") findInPage(document.getElementById("searchstr").value) } function findInPage(str) { var txt, i, found; if (str == "") return false; if (DOM) { win.find(str, false, true); return true } if (NS4) { if (!win.find(str)) while (win.find(str, false, true)) n++; else n++; if (n == 0) alert("未找到指定内容.") } if (IE4) { 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("未找到指定内容.") } } return false } </script>
</head>
<body>
<input type="text" id="searchstr" name="searchstr" style="width: 200px" />
<input type="button" value="屏幕查找" onclick="javascript:findIt();" />
<br />
<p>
网页尺寸大小往往有网页上的图片,视频以及音频或者现在比较少用的flash造成的,如果网页上的这些元素少了,仅仅是文字性的内容,自然整个网页的尺寸就能够降下来,可是如果没有这些元素,网页看起来又太单调,对用户的吸引力不够,特别是一些视频网站,其主要内容更是以视频为主,所以在不能够减少这些元素的应用之后,剩下来的就是要想办法把这些元素进行压缩了,不过对于图片音频和视频而言,可以通过格式的转变还是比较容易实现的!另外对于播放flash,视频音频的控件也能够通过优化代码的方式来实现,这样就能够极大的减少网页的尺寸,让用户实现高速冲浪的快感!</p>
<br />
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: