问题描述
我正在尝试用 Javascript 开发一些代码,将突出显示的文本添加到类中.我想要实现的是使用自定义颜色突出显示文本的能力.
I'm trying to develop some code in Javascript that adds highlighted text to a class. What I want to achieve with this is the ability of text highlighting with a custom color.
我希望它看起来像下面这样:
I want it to kind of look like the following:
window.getSelected = "<span class=\"highlighted\">" + window.getSelected + "</span>"
执行上述代码后,所选文本的背景被span标签包围.
after the above code is executed the selected text's background is surrounded by span tags.
谢谢,
fbr
推荐答案
你会想要研究范围对象,这里有一个很好的总结:
You'll want to look into Range Objects, there is a good summary here:
http://www.quirksmode.org/dom/range_intro.html
浏览器兼容性会是个问题,但基本上,你可以按照你建议的方式获取当前选择,然后将其转换为一个Range,并使用Range对象的方法来查找和拆分现有的DOM节点,并且插入包含所选文本的您自己的 标签.
Browser compatibility will be an issue, but basically, you can get the current selection in the way you suggest, then convert it into a Range, and use the methods of the Range object to find and split the existing DOM nodes, and insert your own <span>
tag containing the selected text.
这并不完全是微不足道的,并且涉及到认真的 DOM 操作,但它是一个有益的主题,让您了解一下.享受!
It's not entirely trivial, and involves getting into serious DOM manipulation, but it's a rewarding subject to get your head around. Enjoy!
这篇关于使用 Javascript 操作突出显示的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!