javascript - 尽管父项已更改,但子项跨度不会更改颜色
问题描述
我想使用这样的函数动态更改整个跨度及其子项的颜色:
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>
如您所见,尽管我成功更改了父跨度的颜色,但子跨度没有更改颜色...
我知道我可以选择子跨度并尝试对它做同样的事情,但是子跨度本身是动态添加的,我们并不总是拥有它......所以我们需要检查它是否存在并尝试更改颜色.. .
所以想要的结果是使用该函数将整个文本颜色更改为绿色。
我想知道是否有更好的解决方案来做到这一点?
解决方案
您可以动态创建新的 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>
推荐阅读
- php - 根据字母对所有类别的 woocommerce 进行索引
- ssl - Let's Encrypt:SSL 证书对域有效,但对特定端口无效
- mongodb - 连接到 MongoDB 的最佳方式
- python - 使用 python 从 .tar.gz 文件中仅提取 jpg 文件
- c# - 与 ASP.NET Core 选项服务绑定时忽略模型属性
- scroll - 使用钩子检测滚动方向
- c++ - 为什么这两个数字比较相等?
- server - 微软 BizTalk HIS SNA
- android - ShapeableImageView 不显示矢量图像
- flutter - (Dart) 小部件不是一种类型