JQuery特效 实现文本关键字多层级着色
当我们在需要对文本中标记关键字的时候,会对关键字进行着色。如果存在不同种类的关键字时,就需要对一段文本的关键字进行多层级着色。
思路
有A,B,C三种关键字,着色优先顺序为A<B<C。
- 提取着色文本的长度,做成着色标记数组:color[ ],color[ ]中所有项记录为空(空表示不着色);
- 按照优先顺序由低到高的顺序,将着色标记记录在color[ ]中,同一个字在多种关键字中有交集时,优先顺序高的着色标记替换color[ ]中优先顺序低的着色标记;
- 循环color[ ]数组对着色文本着色。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>jquery特效 多层级着色</title>
<script src="http://code.jquery.com/jquery-1.8.0.min.js" type="text/javascript"></script>
<style type="text/css">
.text-A-color{background-color:#ff0000;color:#000000;font-weight:bold;}
.text-B-color{background-color:#ff7f00;color:#000000;font-weight:bold;}
.text-C-color{background-color:#0030ff;color:#000000;font-weight:bold;}
</style>
<script type="text/javascript">
//click方法
function btnclick(){
$("#searchTextTest").html($("#text").val());
var vhtml = $("#searchTextTest").html();
var lstClass = new Array();
for(var i=0; i<vhtml.length; i++){
lstClass.push("");
}
//颜色优先顺序 C>B>A
//A
var A_color = $("#A-color").val();
var AClass = "text-A-color";
if (A_color.length > 0){
lstClass = GetColorArr(vhtml, lstClass, A_color, AClass);
}
//B
var B_color = $("#B-color").val();
var BClass = "text-B-color";
if (B_color.length > 0){
lstClass = GetColorArr(vhtml, lstClass, B_color, BClass);
}
//C
var C_color = $("#C-color").val();
var CClass = "text-C-color";
if (C_color.length > 0){
lstClass = GetColorArr(vhtml, lstClass, C_color, CClass);
}
//着色
vhtml = SetColorHtml(vhtml, lstClass);
$("#searchTextTest").html(vhtml);
}
//获取文本数组
function GetIndexAll(str, sub){
debugger;
var arrIdx = new Array();
var idx = -1;
var test = true;
while (test){
idx = str.indexOf(sub, idx + 1);
if (idx < 0){
test = false;
break;
}
arrIdx.push(idx);
}
return arrIdx;
}
//获取着色数组
function GetColorArr(vhtml, lstClass, word, pCss){
var arrIdx = []
arrIdx = GetIndexAll(vhtml, word);
$.each(arrIdx,function(i, idx){
if (idx < 0) {
return;
}
for (var j=0; j < word.length; j++){
lstClass[idx + j] = pCss;
}
});
return lstClass;
}
//文本着色
function SetColorHtml(vhtml, lstClass){
var str = "";
for (var i=0; i<vhtml.length; i++){
if (lstClass[i] != ""){
str += "<span rel='mark' class='" + lstClass[i] + "'>" + vhtml[i] + "</span>";
}else{
str += vhtml[i];
}
}
return str;
}
</script>
</head>
<body>
<div class="">
<span>TEXT</span><input type="text" id="text" />
<div>
<span>A-color-word</span><input type="text" id="A-color" />
<span>B-color-word</span><input type="text" id="B-color" />
<span>C-color-word</span><input type="text" id="C-color" />
<input onclick="javascript:btnclick();" type="button" value="着色" />
</div>
<div id="searchTextTest" >
</div>
</div>
</body>
</html>
请大家多多指教>_<