首页 > 解决方案 > 我该如何解决?DOM javascript渐变不起作用?

问题描述

我需要从“父”元素中获取“子”元素的颜色并从中制作线性渐变,然后将其插入“渐变”元素中。在警报中,我的样式背景颜色重复了几次。我该如何解决?

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>

标签: javascriptfor-loopdomparent-childlinear-gradients

解决方案


您需要删除变量,末尾的尾随符号并在 for 循环之外的元素上设置背景gradientcolorgradient

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>


推荐阅读