我需要从“父”元素中提取“子”元素的颜色并从中提取线性渐变,然后将其插入到“渐变”元素中。在警报中,我的风格 background-color 重复了几次。我该如何解决这个问题?
function myFunction() {
var gradientcolor = "";
var childcolor = document.getElementById("parent").children;
var i;
for (i = 0; i < childcolor.length; i++) {
gradientcolor += childcolor[i].style.backgroundColor + ', ';
console.log(gradientcolor);
document.getElementById("gradient").style.backgroundImage = "linear-gradient(to right, " + gradientcolor + " )"
}
}
<div id="parent">
<div id="child" style="width:50px;height:50px;background-color:rgb(255, 0, 0);"></div>
<div id="child" style="width:50px;height:50px;background-color:rgb(0, 215, 0);"></div>
<div id="child" style="width:50px;height:50px;background-color:rgb(0, 0, 255);"></div>
</div>
<div id="gradient" style="width:150px;height:50px;background-color:#f2f2f2"></div>
<button onclick="myFunction()">Try it</button>
最佳答案
您需要删除 gradientcolor
变量末尾的 ,
符号,并在 for 之外的 gradient
元素上设置背景循环
function myFunction() {
let gradientcolor = "";
let childcolor = document.getElementById("parent").children;
for (let i = 0; i < childcolor.length; i++) {
gradientcolor += childcolor[i].style.backgroundColor + ', ';
}
document.getElementById("gradient").style.background = "linear-gradient(to right, " + gradientcolor.slice(0, -2) + " )"
}
<div id="parent">
<div id="child" style="width:50px;height:50px;background-color:rgb(255, 0, 0);"></div>
<div id="child" style="width:50px;height:50px;background-color:rgb(0, 215, 0);"></div>
<div id="child" style="width:50px;height:50px;background-color:rgb(0, 0, 255);"></div>
</div>
<div id="gradient" style="width:150px;height:50px;background-color:#f2f2f2"></div>
<button onclick="myFunction()">Try it</button>
关于javascript - 我该如何解决? DOM javascript 渐变不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61849273/