如何在 html 中实现自动文本搜索

How to implement Auto Text search in html?

本文关键字:文本 搜索 实现 html      更新时间:2023-09-26

我想向我的网页添加文本搜索。但我希望它自动搜索当用户输入文本而不单击"查找"按钮时。我想删除按钮并使其自动搜索

示例代码

function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);
        
        while (window.find(text)) {
            document.getElementById("button").blur();
            document.execCommand("HiliteColor", false, "yellow");
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}
<input type="text" id="search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">
<div id="content">
    <p>Here is some searchable text with some lápices in it, and more lápices, and some <b>for<i>mat</i>t</b>ing</p>
</div> 

<input type="text" id="search" onkeypress="doSearch(this.value)">

http://www.w3schools.com/jsref/event_onkeypress.asp