首页 > 解决方案 > 尽管父项已更改,但子项跨度不会更改颜色

问题描述

我想使用这样的函数动态更改整个跨度及其子项的颜色:

setTimeout(() => color(), 2500); 

function color() {
  const el = document.getElementById('expand');
  el.style.WebkitTransition = 'color 2s ease-in-out';
  el.style.color = '#9dde07';
}
.colored { 
  color: #fc0303; 
}
<span id="expand">  This forest 
<span class="colored">is</span> 
beautiful.
</span>

如您所见,尽管我成功更改了父跨度的颜色,但子跨度没有更改颜色...

我知道我可以选择子跨度并尝试对它做同样的事情,但是子跨度本身是动态添加的,我们并不总是拥有它......所以我们需要检查它是否存在并尝试更改颜色.. .

所以想要的结果是使用该函数将整个文本颜色更改为绿色。

我想知道是否有更好的解决方案来做到这一点?

标签: javascripthtmlcss

解决方案


您可以动态创建新的 CSS 规则并将颜色应用于元素和所有子元素。这适用于任何类型的组合:

const {sheet} = Object.assign(document.head.appendChild(document.createElement("style")), {type: "text/css" });


setTimeout(() => color(), 2500); 

function color() {
  const el = document.getElementById('expand');
  sheet.rules[sheet.insertRule("#expand,#expand * {transition:color 2s ease-in-out;color:#9dde07!important}")];
}
.colored { 
  color: #fc0303; 
}
<span id="expand">  This forest 
<span class="colored">is</span> 
beautiful
<span class="colored">and</span> 
big.
</span>


推荐阅读