当前位置: 代码迷 >> 综合 >> 页面搜索的简单实现
  详细解决方案

页面搜索的简单实现

热度:12   发布时间:2024-01-17 22:09:06.0

这里页面搜索的实现是简单的HTML元素替换,如果使用的是bootstrap的话会有样式丢失的情况出现,需要重新绑下时间:

 

整个body放在一个dom里面:

<body><div id="window_content">....</div>
</body>

 弹窗在这里:

<div style="width: 600px;position: fixed;top: 50px;left: 20px;z-index: 999; display: none" id="search_key_dom_"><input type="text" id="search_key"><button id="search_btn" >搜索</button><button id="search_top" >上一个</button><button id="search_next">下一个</button><button id="search_cancle_">取消搜索</button>
</div>

css里面加个样式,也可以根据需求自定义:

        .res {/*color: Red;*/background: rgb(215, 48 ,48);color: white;}.result {background: yellow;}

逻辑:

var oldKey = "";var index = -1;var pos = new Array();//用于记录每个关键词的位置,以方便跳转var posy = new Array();//用于记录每个关键词的位置,以方便跳转var oldCount = 0;//记录搜索到的所有关键词总数var previous = function(){index--;index = index < 0 ? oldCount - 1 : index;search();};var next = function (reset){if (index || 0 == index){index++;}if(index==oldCount){index = 0 ;}search(reset);};var  search = function (reset) {if (!detail){detail = require("js/app/detail");}$(".res").addClass("result");$(".result").removeClass("res");//去除原本的res样式var key = $("#search_key").val(); //取key值if (!key) {$(".result").each(function () {//恢复原始数据$(this).replaceWith($(this).html());});oldKey = "";return; //key为空则退出}if (oldKey != key || reset) {//重置index = 0;$(".result").each(function () {$(this).replaceWith($(this).html());});pos = new Array();posy = new Array();var regExp = new RegExp(key+'(?!([^<]+)?>)', 'g');//正则表达式匹配$("#window_content").html($("#window_content").html().replace(regExp, "<span id='result" + index + "' class='result'>" + key + "</span>")); // 高亮操作detail.typeSwitch();detail.kliSearch();$("#key").val(key);oldKey = key;$(".result").each(function () {pos.push($(this).offset().top);posy.push($(this).offset().left);//隐藏的dom元素不提供搜索功能var domStyle = this.getBoundingClientRect();if (!(domStyle && domStyle.bottom > 0)){$(this).removeClass("result");}});oldCount = $(".result").length;}$(".result:eq(" + index + ")").addClass("res");//当前位置关键词改为红色字体$(".result:eq(" + index + ")").removeClass("result");//移除之前的样式$("body").scrollTop(pos[index] - 100 );//跳转到指定位置window.scrollTo(0,pos[index]-500);}var  redisplay = function () {//恢复原始数据$(".result").each(function () {$(this).replaceWith($(this).html());});$(".res").each(function () {$(this).replaceWith($(this).html());});index = 0;}

参考:JSP页面 CTRL+F 功能实现

  相关解决方案