纯JS搜索页面内容-我的扩展版本
我扩展了什么?
1.不区分大小写,且替换后保留原大小写内容.
2.自动滚动到所属位置.
时间比较赶 也比较粗糙.
原作 张鑫旭
-------
$.tmp_textSearch_str = "";
$.fn.textSearch = function(str, options) { //纯JS字符串搜索
var defaults = {
divFlag: true,
divStr: " ",
markClass: "",
markColor: "red",
nullReport: true,
scroll: 1,
callback: function() {
return false;
}
};
var sets = $.extend({}, defaults, options || {}), clStr;
if (sets.markClass) {
clStr = "class='" + sets.markClass + "'";
} else {
clStr = "style='color:" + sets.markColor + ";'";
}
//对前一次高亮处理的文字还原
$("span[data-keyrole='mark']").each(function() {
var text = document.createTextNode($(this).text());
$(this).replaceWith($(text));
});
//字符串正则表达式关键字转化
$.regTrim = function(s) {
var imp = /[\^\.\\\|\(\)\*\+\-\$\[\]\?]/g;
var imp_c = {};
imp_c["^"] = "\\^";
imp_c["."] = "\\.";
imp_c["\\"] = "\\\\";
imp_c["|"] = "\\|";
imp_c["("] = "\\(";
imp_c[")"] = "\\)";
imp_c["*"] = "\\*";
imp_c["+"] = "\\+";
imp_c["-"] = "\\-";
imp_c["$"] = "\$";
imp_c["["] = "\\[";
imp_c["]"] = "\\]";
imp_c["?"] = "\\?";
s = s.replace(imp, function(o) {
return imp_c[o];
});
return s;
};
$(this).each(function() {
var t = $(this);
str = $.trim(str);
if (str === "") {
//alert("Keyword is empty.");
return false;
} else {
//将关键字push到数组之中
var arr = [];
if (sets.divFlag) {
arr = str.split(sets.divStr);
} else {
arr.push(str);
}
}
var v_html = t.html();
//删除注释
v_html = v_html.replace(/<!--(?:.*)\-->/g, "");
//过滤HTML片段
var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g;
var a = v_html.match(tags), test = 0;
$.each(a, function(i, c) {
if (!/<(?:.|\s)*?>/.test(c)) {//非标签
//开始执行替换
$.each(arr, function(index, con) {
if (con === "") {
return;
}
var reg = new RegExp("(" + $.regTrim(con) + ")", "ig");
if (reg.test(c)) {
//正则替换
c = c.replace(reg, "#♂spstart# $1 #♂spend#");
test = 1;
}
});
c = c.replace(/#♂spstart#/g, "<span data-keyrole='mark' " + clStr + ">").replace(/#♂spend#/g, "</span>");
a[i] = c;
}
});
//将支离数组重新组成字符串
var new_html = a.join("");
$(this).html(new_html);
if (test === 0 && sets.nullReport) {
alert("No result found in this page.");
return false;
}
sets.callback();
if (sets.scroll) {
//自动滚动
$.tmp_textSearch_str = $.tmp_textSearch_str || str;
if ($.tmp_textSearch_str == str) {
$.tmp_textSearch_scollCount = $.tmp_textSearch_scollCount === undefined ? 0 : ($.tmp_textSearch_scollCount + 1);
} else {
$.tmp_textSearch_str = str;
$.tmp_textSearch_scollCount = 0;
}
var span = $("span[data-keyrole='mark']")[$.tmp_textSearch_scollCount];
if (!span) {
$.tmp_textSearch_scollCount = 0;
span = $("span[data-keyrole='mark']")[0];
}
var toTop = $(span).offset().top - 10;
$('html,body').animate({scrollTop: toTop}, window.navigator.appName == 'Opera' ? 0 : 100);
}
});
};
浙公网安备 33010602011771号