简体   繁体   English

如何通过Javascript更改html td背景颜色?

[英]How to change html td background colour through Javascript?

<style type="text/css">
    td.a{
        background: yellow
    }
</style>

<table><td class="a"></td></table>

Above is a html/css code snippet. 上面是一个html / css代码段。 From it, you can know that the background colour of td portion is in yellow. 从中可以知道td部分的背景颜色为黄色。

Later, I have added a html select drop down component. 后来,我添加了一个html select下拉组件。 I hope to change the background colour from yellow to blue when I select another select drop down value. 我希望在选择另一个选择下拉值时将背景颜色从黄色更改为蓝色。 but I do not know how to do. 但我不知道该怎么办。

This should be a question related to changing css through Javacript. 这应该是与通过Javacript更改css有关的问题。 It is quite similar with this How to change HTML background with JavaScript Function? 与此非常相似如何使用JavaScript函数更改HTML背景? but u can see that my td component does not have id, it just has class. 但是您可以看到我的td组件没有id,而只有class。

Hope someone can help me, thank you. 希望有人能帮助我,谢谢。

Assuming the colour you want to change the background of the cells (I'm assuming you'll have more than just the one) to is newColor then; 假设您要更改单元格背景的颜色(我假设您将不止一个)变为newColor;

var tds = document.getElementsByClassName('a');
for (var x = 0; x < tds.length; x++) {
  tds[x].style.background = newColor;
}

For changing all elements with the class name 用于更改具有类名称的所有元素

var elements = document.getElementsByClassName("a");
for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor="blue";
}

Or to change a single element, as long as you know it's position. 或更改单个元素,只要您知道它的位置即可。

var elements = document.getElementsByClassName("a");
elements[positon].style.backgroundColor="blue";//in your example position would be 0

If you give your element an id you can use the following 如果为您的元素指定ID,则可以使用以下代码

document.getElementById("idforelement").style.backgroundColor = "blue";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM