您当前的位置: > 个人博客 > javascript

js搜索高亮

2017-06-23 11:33:36 点击量:22 标签: 收藏本文

<script type="text/javascript">
    function encode(s) {
        return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/([\\\.\*\[\]\(\)\$\^])/g, "\\$1");
    }
    function decode(s) {
        return s.replace(/\\([\\\.\*\[\]\(\)\$\^])/g, "$1").replace(/>/g, ">").replace(/</g, "<").replace(/&/g, "&");
    }
    function highlight(s) {
        var s = $('#s_content').val();
        console.log(s);
        if (s.length == 0) {
            alert('搜索关键词未填写!');
            return false;
        }
        s = encode(s);
        var obj = document.getElementById("bgf");
        var t = obj.innerHTML.replace(/<span\s+class=.?highlight.?>([^<>]*)<\/span>/gi, "$1");
        obj.innerHTML = t;
        var cnt = loopSearch(s, obj);
        t = obj.innerHTML
        console.log(t);
        var r = /{searchHL}(({(?!\/searchHL})|[^{])*){\/searchHL}/g;
        t = t.replace(r, "<span class='highlight'>$1</span>");
        obj.innerHTML = t;
    }
    function loopSearch(s, obj) {
        var cnt = 0;
        if (obj.nodeType == 3) {
            cnt = replace(s, obj);
            return cnt;
        }
        for (var i = 0, c; c = obj.childNodes[i]; i++) {
            if (!c.className || c.className != "highlight")
                cnt += loopSearch(s, c);
        }
        return cnt;
    }
    function replace(s, dest) {
        var r = new RegExp(s, "g");
        var tm = null;
        var t = dest.nodeValue;
        var cnt = 0;
        if (tm = t.match(r)) {
            cnt = tm.length;
            t = t.replace(r, "{searchHL}" + decode(s) + "{/searchHL}")
            dest.nodeValue = t;
        }
        return cnt;
    }
    highlight();
</script>
<style type="text/css">
        .highlight{background:green;font-weight:bold;color:white;}
    </style>
CONTACT US

地址:武汉腾讯大楚网

电话:1997567510

电子邮件:5367604@qq.com

若需在线联系,可直接点击下面按钮咨询