JS模拟浏览器CTRL+F功能

<input id="key" placeholder="关键词搜索" class="form-control" type="search"/>
<input type="button" class="btn" value="下一个" onclick="next()" />
<input type="button" class="btn" value="上一个" onclick="previous()" />
<span id="searchInfo"></span>


var oldKey = "";
    var index = -1;
    var pos = new Array();//用于记录每个关键词的位置,以方便跳转
    var oldCount = 0;//记录搜索到的所有关键词总数

    function previous(){
        index--;
        index = index < 0 ? oldCount - 1 : index;
        search();
    }
    function next(){
        index++;
        //index = index == oldCount ? 0 : index;
        if(index==oldCount){
            index = 0 ;
        }
        search();
    }

    function search() {
        $(".result").removeClass("res");//去除原本的res样式
        var key = $("#key").val(); //取key值
        if (!key) {
            console.log("key为空则退出");
            $(".result").each(function () {//恢复原始数据
                $(this).replaceWith($(this).html());
            });
            oldKey = "";
            $("#searchInfo").text("");
            return; //key为空则退出
        }
        if (oldKey != key) {
            console.log("进入重置方法");
            //重置
            index = 0;
            $(".result").each(function () {
                $(this).replaceWith($(this).html());
            });
            pos = new Array();
            var regExp = new RegExp(key+'(?!([^<]+)?>)', 'ig');//正则表达式匹配
            //不用.table去遍历这样会导致点击方法失效,直接替换最小单位的td就行
            $("td").each(function () {
                $(this).html($(this).html().replace(regExp, "<span id='result" + index + "' class='result'>" + key + "</span>")); // 高亮操作
            })
            $("#key").val(key);
            oldKey = key;
            $(".result").each(function () {
                if($(this).offset().top == 0){
                    return;
                }
                //先回到页面最顶部,否则会出现定位不准确,导致上一个下一个无法跳转至目标
                $("#content-main").scrollTop(0);
                pos.push($(this).offset().top);
            });
            oldCount = $(".result").length;
        }

        $(".result:eq(" + index + ")").addClass("res");//当前位置关键词改为红色字体
        if(pos.length > 0){
            $("#searchInfo").text("当前第" + (index+1) + "个,共" + pos.length + "个结果");
            $("#content-main").scrollTop(pos[index] - 120);//跳转到指定位置
        }else{
            $("#searchInfo").text("共0个结果");
        }
    }


版权声明:本文为qq_42021843原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。