使用 JavaScript 一次突出显示网页上的每个单词
一次一个地突出显示页面上每个单词的最佳方式是什么?我认为这些单词应该分解成一个数组并以这种方式迭代,但是最好的方法是什么?
我已经知道如何执行字符串替换和设置单个元素的样式,技巧是以最有效的方式对页面上的每个单词执行此操作,一次一个。
What's the best way to visually highlight each word on the page, one at a time? I figure that the words should be broken up into an array and iterated over that way, but what's the best way to do so?
I already know how to perform string replacements and style individual elements, the trick is to do this on each word on the page, one at a time, in the most efficient manner.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要获取某些内容的innerHTML,然后将其分割到空间中,然后用不同的类将每个单词包裹在一个跨度中,并将其设置回文本的位置。
使用 css 给它们设置不同的颜色或其他东西。
我不确定你打算如何“一次一个”地突出显示它们。这涉及动画什么的吗?
you will need to grab the innerHTML of something, then split it over space, then wrap a span around each word with different classes, and set it back in place of text.
use css to color these differently or something.
i am not sure how you plan to highlight them "one at a time". does that involve an animation or something?
这很简单。
It's simple.
它实际上取决于文本。如果您想要替换的区域内有标签,那么我不怀疑innerHTML 上的正则表达式替换效果不会那么好。
像这样:
另一种方法是迭代 DOM 中的文本节点。如果您的目标不是 IE,则可以使用 TreeWalker 轻松获取集合按文档顺序排列的文本节点。如果您需要以 IE 为目标,这似乎是 迭代文本的其他方法的一个很好的总结节点
然后,想法是迭代文本节点,对节点数据进行正则表达式分割,并将每个子节点包装在带有背景的跨度中以突出显示。
这是一个相当仓促编写的示例,但它应该可以让您有所了解。
它不会是最快的可用方法,但它应该比innerHTML 上的正则表达式替换更准确。修改循环以使用 window.setTimeout 来设置突出显示动画也不是那么困难。
It actually kind of depends on the text. If you've got tags within the area you're wanting to replace, the regex replace on the innerHTML won't work that well I don't suspect.
Something like this:
The alternative is to iterate over text nodes within the DOM. If you're not targeting IE, you can use the TreeWalker to easily get a collection of text nodes in document order. If you need to target IE, this seems to be a good summary of other ways to iterate text nodes
Then the idea would be to iterate over the text nodes, do the regex split on the node data and wrap each child node in a span with background to highlight.
Here's a fairly hastily written example, but it should give you the idea.
It won't be the fastest method available, but it should be more accurate than a regex replace on the innerHTML. It's also not that difficult to modify the loop to use window.setTimeout to animate the highlighting.
这是我的工作但未完善的代码,它可以一次突出显示每个单词,并在到达每行中的最后一个单词时滚动:
Here is my working but unrefined code that achieves highlighting each word one at a time as well as scrolling when the last word in each line is reached: