使用 JavaScript 更改 HTML 中的文本背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7659659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change Text BackGround Color in HTML using JavaScript
提问by Saurabh Saxena
<ul>
<li>
<span class="name">Tortilla de blé</span>
</li>
</ul>
This is the original source. I need to change the background Color of just the textin the tag. I have used css property background-color for it. But it is changing the color of the whole list item. i have to change the background color only by using javascript.
这是原始来源。我只需要更改标签中文本的背景颜色。我已经为它使用了 css 属性背景色。但它正在改变整个列表项的颜色。我必须仅使用 javascript 更改背景颜色。
var ea = document.getElementsByClassName('name');
for(var i = 0; i < ea.length; i++)
ea[i].style.backgroundColor = "yellow";
(Changed the Older Script as that was not correct, mistakenly written)
(更改了旧脚本,因为它不正确,写错了)
My Result:
我的结果:
Expected Result:What could i do to just highlight the text in the tag and not the whole tag.
预期结果:我该怎么做才能突出显示标签中的文本而不是整个标签。
I have produced the expected result by editing the source code like below:
我通过编辑源代码产生了预期的结果,如下所示:
<ul>
<li>
<span class="name"><font style="bakground-color:yellow">Tortilla de blé</font></span>
</li>
</ul>
By Embedding font tag to the text which is not possible with the javascript. I have done this with the help of Inspect Elementfeature of Google Chrome
通过将字体标签嵌入到 javascript 无法实现的文本中。我是在 Google Chrome的Inspect Element功能的帮助下完成的
回答by Alex K.
Your js example is not valid and should not do anything ...
您的 js 示例无效,不应执行任何操作...
You need to set the style on each span element;
您需要在每个 span 元素上设置样式;
var ea = document.getElementsByClassName('name');
for(var i = 0; i < ea.length; i++)
ea[i].style.backgroundColor = "yellow";
回答by Alex K.
Tried with jQuery, http://jsfiddle.net/sameerast/gT9eh/
尝试使用 jQuery, http://jsfiddle.net/sameerast/gT9eh/
回答by grw
As explained above - your JS is not valid. For starters, the function name is 'getElementsByClassName' rather than 'getElementByClaassName'.
如上所述 - 您的 JS 无效。首先,函数名称是“getElementsByClassName”而不是“getElementByClaassName”。
You then need to have it loop through the elements and set their properties individually. JQuery will give you a nice shortcut as outlined by Sameera.
然后,您需要让它循环遍历元素并单独设置它们的属性。正如 Sameera 所概述的,JQuery 将为您提供一个很好的快捷方式。