在指定的div中搜索内容,并滚动显示到当前搜索到的内容处

时间:2023-03-09 01:49:21
在指定的div中搜索内容,并滚动显示到当前搜索到的内容处

我想要的是页面中有个带滚动条的div对象,里面有很多内容,想要用js搜索到div中的某个字符串内容,然后将div的滚动条滚动到搜索到的内容处显示,自动定位。
先是查找页面中的内容,然后将找到的内容创建textRange,然后找到内容的上层容器对象,利用JQuery的功能,将这个上层窗口对象位置和div位置运算一下后,把div的滚动条滚动到这个容器位置。

                  //在指定的div对象中搜索内容,并定位滚动div的滚动条到搜索
//在整个文本中查找第几个,从0开始
var nextIndex = ;
//上一次需要查找的字符串
var searchValue = ''; function findInPage(searchText) { //在指定的div对象中搜索内容,并定位滚动div的滚动条到搜索内容位置显示
//判断搜索字符是否为空
if (!searchText) {
alert('请输入要搜索的内容');
return;
}
var textvalue = searchText;
var divObj = document.getElementById("div"); //判断搜索条件是否已经改变
if (searchText && searchText != searchValue && nextIndex > ) {
searchValue = searchText;
nextIndex = ;
} else {
searchValue = searchText;
} if (document.all) {
txt = document.body.createTextRange();
//搜索str
var found = '';
//查找第nextIndex个的字符串。之所以要用循环,是因为TextRange对象每次都是新生成的,所以查找初始位置每次都会还原。那么要查找第n次出现的字符串,就需要调用findText()方法多次,且每次查找都要重新设置开始位置和结束位置。
for (i = ; i <= nextIndex && (found = txt.findText(searchValue)) == true; i++) {
txt.moveStart("character", );
txt.moveEnd("textedit");
}
//选中本次查找的字符串
if (found) {
//这里设置为-1,表示为倒序查找。之所以要这样做,是因为此时我们已经查找到了第nextIndex出现的字符串,那么此时如果设置为倒序查找,且将开始位置设置为末尾,那么此时调用findText()方法查找,则会刚好查到我们上一次查到的字符串
txt.moveStart("character", -);
txt.findText(searchValue);
txt.select();
//滚动屏幕到合适位置
//txt.scrollIntoView(false);
var container = $(divObj);
var rng = document.selection.createRange();
var scrollTo = $(rng.parentElement());
//var scrollTo = $('#bfbf'); container.scrollTop(
scrollTo.offset().top - container.offset().top + container.scrollTop()
);
nextIndex++;
} else {
//循环查找
if (nextIndex > ) {
nextIndex = ;
findInPage(divObj, searchValue);
} else {
alert('没有搜索到“' + textvalue + '”');
}
}
} else {
//循环查找
window.find(searchValue, false, true);
}
}