用于Internet Explorer的搜索页面功能
问题描述:
我需要在我正在处理的网站中添加搜索页面功能。我在网上找到了一个,它在Firefox和Chrome中运行良好但在IE中根本没有。我认为我没有编写这段代码的事实使得调试变得特别困难。任何帮助或指导表示赞赏!
I need to put a search page function in the site that I'm working on. I found one online and it works great in Firefox and Chrome but not at all in IE. I think the fact that I didn't write this code is making it particularly hard to debug. Any help or guidance is appreciated!
HTML
<form id="f1" name="f1" action="javascript:void(0)" onsubmit="searchpage()" >
<input id="t1" type="text" name="t1" />
<input id="button" type="submit" value="FIND" name="b1" onclick="searchpage()" />
</form>
JAVASCRIPT
JAVASCRIPT
function searchpage() {
if (document.getElementById("t1").value != null && this.document.getElementById("t1").value != '') parent.findString(document.getElementById("t1").value);
return false;
}
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) {
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;
}
同样重要的是要注意虽然这适用于Firefox和Chrome, 找不到字符串!警告框不起作用
it is also important to note that while this works in Firefox and Chrome, the "string not found!" alert box doesn't work
答
这是一个从我的另一个答案。
演示: http://jsfiddle.net/MRp2G/5/
代码:
function doSearch(text) {
var sel;
if (window.find && window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
sel.collapseToEnd();
}
window.find(text);
} else if (document.selection && document.body.createTextRange) {
sel = document.selection;
var textRange;
if (sel.type == "Text") {
textRange = sel.createRange();
textRange.collapse(false);
} else {
textRange = document.body.createTextRange();
textRange.collapse(true);
}
if (textRange.findText(text)) {
textRange.select();
}
}
}