查找页面内容方法document.body.createTextRange(),兼容火狐,ie的写法

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在HTML页面内实现查找功能,可以使用JavaScript。你可以使用JavaScript提供的`window.find()`方法来实现页面查找。下面是一个简单的示例: ```html <!DOCTYPE html> <html> <head> <title>页面查找</title> <script> function searchWithinPage() { var searchTerm = document.getElementById('searchTerm').value; if (searchTerm) { if (window.find && window.getSelection) { document.designMode = "on"; var sel = window.getSelection(); sel.collapse(document.body, 0); while (window.find(searchTerm)) { document.execCommand("HiliteColor", false, "yellow"); sel.collapseToEnd(); } document.designMode = "off"; } else if (document.body.createTextRange) { var textRange = document.body.createTextRange(); while (textRange.findText(searchTerm)) { textRange.execCommand("BackColor", false, "yellow"); textRange.collapse(false); } } } } </script> </head> <body> <h1>页面查找示例</h1> <input type="text" id="searchTerm" placeholder="输入要查找内容"> <button onclick="searchWithinPage()">查找</button> <p>这是一个示例段落,用于演示页面查找功能。</p> <p>在这个段落中,你可以输入要查找内容,并点击“查找”按钮来查找并高亮匹配的文本。</p> </body> </html> ``` 上面的示例代码中,我们使用了一个输入框和一个按钮,当用户输入要查找内容并点击按钮时,会调用`searchWithinPage()`函数来执行查找操作。 在`searchWithinPage()`函数中,我们首先获取用户输入的查找词,然后使用`window.find()`方法进行查找。如果`window.find()`方法可用,我们将打开文档的设计模式,并通过循环遍历来查找并高亮匹配的文本。 如果`window.find()`方法不可用,我们将回退到使用`document.body.createTextRange()`和`findText()`方法来进行查找。 注意:这只是一个简单的示例,实际应用中可能需要更多的逻辑和样式来满足你的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值