javascript - 我该如何解决? DOM javascript 渐变不起作用?

标签 javascript for-loop dom parent-child linear-gradients

我需要从“父”元素中提取“子”元素的颜色并从中提取线性渐变,然后将其插入到“渐变”元素中。在警报中,我的风格 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/

相关文章:

java - 如何访问列表

javascript - 如何使用模优化函数?

java - 循环遍历ArrayList并仅打印具有特定属性的对象

javascript - 在 div 加载到 dom 后,在 div 上附加一个按钮

javascript - 如何在生成的 contentEditable div 的顶部和底部附加固定的不可编辑内容?

javascript - td 的 onclick 更改 td css

javascript - 在 Javascript 中使用 map 函数返回新值

javascript - jQuery 选择器忽略了来自单独上下文的元素

javascript - Angular 中的单词替换过滤器的正则表达式问题

javascript - 如何以 Angular 将参数传递给服务中的函数