javascript

当前位置:首页 > 前端 > javascript

搜索当前页面查找内容

<form> <input type="search" id="searchInput" placeholder="Search..."> <button type="button" onclick="searchFunction()">Sea...
<form>
    <input type="search" id="searchInput" placeholder="Search...">
    <button type="button" onclick="searchFunction()">Search</button>
</form>

<script>
    function searchFunction() {
        var searchText = document.getElementById('searchInput').value;
        if (searchText) {
            if (window.find && window.getSelection) {
                document.designMode = "on";
                var sel = window.getSelection();
                sel.collapse(document.body, 0);
                while (window.find(searchText)) {
                    document.execCommand("HiliteColor", false, "yellow");
                    sel.collapseToEnd();
                }
                document.designMode = "off";
            } else if (document.body.createTextRange) {
                var textRange = document.body.createTextRange();
                while (textRange.findText(searchText)) {
                    textRange.execCommand("BackColor", false, "yellow");
                    textRange.collapse(false);
                }
            }
        }
    }
</script>


相关内容

文章评论

表情

共 0 条评论,查看全部
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~