javascript - 同时多个CreateTextRange
我有下面的 javascript 函数,当传递诸如“部门”之类的单词时,它将以红色突出显示屏幕上找到的“部门”的第一个实例。但是,我希望这段代码突出显示给定单词的所有实例。
function findString (str) {
var TRange=null;
var strFound;
var TRange = self.document.body.createTextRange();
TRange.findText(str);
TRange.execCommand('foreColor', false, "#ff0000");
return;
}
I have the below javascript function, which when passed a word such as "Department" will highlight in red the first instance of "Department" found on the screen. However, i would like this code to highlight ALL instances of the given word.
function findString (str) {
var TRange=null;
var strFound;
var TRange = self.document.body.createTextRange();
TRange.findText(str);
TRange.execCommand('foreColor', false, "#ff0000");
return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这段代码看上去已经做到了,但是比较草率,有点过分。我确信必须有一种更短的方法来做到这一点,而不是在同一个函数中几乎重复我的 execCommand 行两次。
This code seems to have done it, but it is sloppy and a little excessive. I'm sure there must be a shorter way to do it rather than almost duplicating my execCommand line twice in the same function.
看一下这个链接:http://www.nsftools.com/misc/SearchAndHighlight.htm< /a>
该页面上使用的脚本与您正在采用的方法不同,但最终结果正是您正在寻找的。
Take a look at this link: http://www.nsftools.com/misc/SearchAndHighlight.htm
The script used on that page is a different approach to what you're taking but the end result is exactly what you're looking for.