javascript-修改html元素的css父级

时间:2018-11-26 18:06:03

标签: javascript html css

因此,我有一个与<td>相匹配的选择器。该<td>继承自CSS类。我们称之为item

item.style.backgroundImage

返回"",但

window.getComputedStyle(item).backgroundImage

返回

"url("http://some-url.com")"

我想修改css类,以使backgroundImage对所有继承者来说都是其他东西。

我还无法弄清楚该怎么做!我可以更改单个元素的backgroundImage,但是我不知道如何获取最初定义backgroundImage的类对象。

3 个答案:

答案 0 :(得分:0)

为目标类编写新的CSS,并将其放在<style>中,并将其附加到head标签。

var style = '<style>.item {background: red !important}</style>';
document.querySelector('head').innerHTML += style;
.item {
  width: 50px;
  height: 50px;
  border: 1px solid #000;
  background: green;
}
<div class="item"></div>
<div class="item"></div>

答案 1 :(得分:0)

您可以使用unset重置继承的属性。请参见下面的代码段。第二个单元格(iddontInherit)将不会收到background-color属性。

td {
  background-color: #f0f0ff;
}

td#dontInherit {
  background-color: unset;
}
<table>
  <tr>
    <td id="inherit">
      Inherited
    </td>
    <td id="dontInherit">
      Not inherited
    </td>
  </tr>
</table>

答案 2 :(得分:0)

我还要在@Mohammad的答案中添加一件事。

如果您希望将其用于动态类,则可以获取className并更改其样式,然后将其添加到head标签。

请参见下面的代码段

var item = document.querySelector("#itemA");

var style = '<style>.'+item.className+' {background-image: url("https://www.beautycolorcode.com/8b0000.png") }</style>';

document.querySelector('head').innerHTML += style;
td{
  background-image: url('https://www.beautycolorcode.com/3a4662.png');
  color:white;
  width:300px;
  height:40px;
  font-family:"Calibri";
}
<table>
  <tr><td id="itemA" class="item-A">A for Apple</td></tr>
  <tr><td class="item-B">B for Ball</td></tr>
  <tr><td class="item-C">C for Cat</td></tr>
  <tr><td class="item-A">A for Ant</td></tr>
</table>

默认情况下,您可以看到它是蓝色背景图像。我已使用ID选择器动态将.item-A类的颜色更改为红色。