javascript完成浏览器Ctrl+F页面搜刮功用

html构造代码

<div>
    <input id="search" type="text" placeholder="输入当前章节要搜刮内容..."/>
    <span id="search-btn" style="cursor: pointer">搜刮</span>
</div>
<div id="content">
    <p>这是要搜刮的内容哦!!</p>
</div>

javascript代码

<script>
    var content = $('#content').html();
    $('#search-btn').click(function () {
        $('#content').html(content);
        var searchText = $('#search').val();
        if (searchText.length == 0) {
            return false;
        }
        var regExp = new RegExp(searchText, 'g');
        var newHtml = content.replace(regExp, '<span id="result" style="background:yellow;color:red;">' + searchText + '</span>');
        $('#content').html(newHtml);
        var X = $('#result').offset().top;
        var Y = $('#result').offset().left;
        window.scrollTo(X, Y);
    });
</script>
    原文作者:klinson
    原文地址: https://segmentfault.com/a/1190000008830839
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞