使用Javascript更改HTML标记中特定文本的颜色 [英] Change color of specific text within HTML tags using Javascript
问题描述
< span id =span> Lorem ipsum dolor sit amet,consectetur adipisicing elit, sed do eiusmod tempor< span>
如何在不修改<$ c $的情况下更改上面任何单词的颜色颜色(我知道我可以把另一个 span
标签放在 document.getElementById(text)。style.color =red;
。但是,我想搜索单词标签(也许使用RegExp)并动态改变其颜色。 解决方案
。所以你要么在源代码中这样做,要么稍后通过操作DOM(在你的情况下,通过jQuery)来完成。
例如:
var span = $(#span); span.html(span.html()。replace(/ dolor /,'< span style =color:red> $ < / span>'));
< ; script src =https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js>< / script>< span id =span> Lorem ipsum dol sit sit,,,ad ad ad&&&&&&&&&$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b 替换字符串中的 $&
是找到的单词。在上文中,只有第一次出现才会被取代;要替换多个匹配项,请在正则表达式的末尾添加 g
( / dolor / g
)。 p>
请注意,如果您有任何事件处理程序附加到 span
内的任何元素,则它们将被删除,如跨度的内容被删除,然后被替换。 (因为你的例子在 span
中根本没有任何元素,我认为情况并非如此,但我认为我应该提及它。)
The question says it all. For example I have the following HTML code:
<span id="span">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor<span>
How do I change the color of the color of any word from above without modifying the span
above(I know I could have put another span
tag with an id="text"
and used document.getElementById("text").style.color="red";
. But instead of this I want to search for the word in the tag(maybe using RegExp) and change it's color dynamically.
解决方案 You can't do it without modifying the contents of the span. So you either do that in the source, or you do it later by manipulating the DOM (in your case, via jQuery).
So for instance:
var span = $("#span");
span.html(span.html().replace(/dolor/, '<span style="color: red">$&</span>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="span">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor</span>
The $&
in the replacement string is the word that was found. In the above, only the first occurrence would be replaced; to replace multiple occurrences, add a g
to the end of the regular expression (/dolor/g
).
Note that if you have any event handlers attached to any elements within the span
, they will get removed by this, as the contents of the span get removed and then replaced. (As your example doesn't have any elements at all within the span
, I figured that wouldn't be the case, but figured I should mention it.)
这篇关于使用Javascript更改HTML标记中特定文本的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!