我需要从“父”元素中获取“子”元素的颜色,并从中进行线性渐变,然后将其插入“渐变”元素中。在警报中,我的样式背景颜色重复了几次。我该如何解决?
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>