javascript - 我该如何解决?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>
解决方案
您需要删除变量,
末尾的尾随符号并在 for 循环之外的元素上设置背景gradientcolor
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>
推荐阅读
- vba - 更改一组 ActiveX 标签的名称
- php - PHP Twitter - 库 tmhOAuth:错误准备参数
- shopify - Shopify 结帐页面上的博客对象为空
- ruby - 从 Ruby 数组中导出矩阵并进行可视化
- reactjs - 反应 Web 开发服务器未实时检测到对 sass 文件的更改
- java - 如何按除第一个字母之外的所有内容对字符串数组进行排序
- python - Pytorch/numpy/python 高效插值损坏数据
- bash - 使用 jq 将 JSON 响应转换为键值对
- java - 杰克逊:反序列化时允许嵌套或“平面”收集
- gatsby - Gatsby + contentful + Netlify 的私人/登录部分