You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将<h1>元素的颜色值批量复制到<path>元素中?

解决方法:遍历所有元素同步颜色

你的问题出在document.querySelectorAll('#my_element svg path')[0]只选取了第一个元素,要让所有都应用颜色,需要遍历querySelectorAll返回的NodeList中的每一个元素。

方案1:使用forEach遍历(现代浏览器支持)

修改JavaScript代码,获取所有后用forEach循环设置fill样式:

const mycolor_element = document.querySelectorAll('#my_id h1')[0]; 
const my_value = window.getComputedStyle(mycolor_element).color;
// 获取所有path元素并遍历设置颜色
document.querySelectorAll('#my_element svg path').forEach(path => {
  path.style.fill = my_value;
});

方案2:使用for循环(兼容旧浏览器)

如果需要兼容不支持NodeList.forEach的旧浏览器,可使用传统for循环:

const mycolor_element = document.querySelectorAll('#my_id h1')[0]; 
const my_value = window.getComputedStyle(mycolor_element).color;
const paths = document.querySelectorAll('#my_element svg path');
// 逐个遍历path元素设置颜色
for (let i = 0; i < paths.length; i++) {
  paths[i].style.fill = my_value;
}

额外优化:简化元素选取

可以用querySelector代替querySelectorAll()[0],直接获取匹配的第一个元素,代码更简洁:

const mycolor_element = document.querySelector('#my_id h1'); 
const my_value = window.getComputedStyle(mycolor_element).color;
document.querySelectorAll('#my_element svg path').forEach(path => {
  path.style.fill = my_value;
});

执行以上代码后,所有元素都会同步

的橙色值。

内容的提问来源于stack exchange,提问作者w2019s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:15:44