我有几个背景颜色不同的部分。
我需要根据这些部分动态创建 div。
到目前为止我没有担心。
我想要得到的结果是,每个 div 在背景中都有不同的颜色,采用各部分的颜色。
我可以用 CSS 得到这个结果
HTML:
<section class="l-section js-section"></section>
<section class="l-section js-section"></section>
<section class="l-section js-section"></section>
<section class="l-section js-section"></section>
<section class="l-section js-section"></section>
<div class="l-container-test js-container-test"></div>
SCSS:
.l-section{
height: 100vh;
width: 100vw;
&:nth-child(1){
background-color: red;
}
&:nth-child(2){
background-color: green;
}
&:nth-child(3){
background-color: yellow;
}
&:nth-child(4){
background-color: blue;
}
&:nth-child(5){
background-color: pink;
}
}
.l-container-test{
display: flex;
height: 100vh;
width: 100vw;
& > * {
flex: 1;
}
& :nth-child(1){
background-color: red;
}
& :nth-child(2){
background-color: green;
}
& :nth-child(3){
background-color: yellow;
}
// and so on....
}
JS:
function createDivs(){
let fragment = document.createDocumentFragment();
let div = document.createElement(`div`);
div.className = `l-div js-div`;
const container = document.querySelector(`.js-container-test`);
const sections = document.querySelectorAll(`.js-section`);
const divs = document.querySelectorAll(`.js-div`);
let arrColors = [];
fragment.appendChild(div);
for(let i = 0; i < 10; i++){
container.appendChild(fragment.cloneNode(true));
}
sections.forEach(section => {
colors = window.getComputedStyle(section).getPropertyValue(`background-color`);
arrColors.push(colors)
})
console.log(arrColors);
// EDIT
arrColors.forEach((color, index) => {
divs[index].style.backgroundColor = color;
})
}
createDivs();
这是我的工作示例:https://jsfiddle.net/CedGrvl/e476kvsn/40/
但我认为如果我可以用 js 处理这些颜色,除非我错了,否则会更容易。如果我添加 div,我希望颜色相互跟随。
知道我的 div 仍然多于部分,我希望颜色顺序是合乎逻辑的。如果从上到下的部分是红色、绿色、蓝色...div 应该是红色、蓝色、绿色、红色、蓝色、蓝色、绿色...
我的逻辑可能有误,我不一定要寻找纯粹简单的解决方案,但至少要寻找一些线索
提前致谢
编辑:
我只设法在第一个上涂上颜色,我明白为什么。我必须弄清楚其他潜水是彩色的。
最佳答案
好吧,我想通了
https://jsfiddle.net/CedGrvl/cp0zbx8t/1/
function createDivs(){
const container = document.querySelector(`.js-container-test`);
const sections = document.querySelectorAll(`.js-section`);
let arrColors = [];
let arrDivs = [];
let fragment = document.createDocumentFragment();
let div = document.createElement("div");
div.className = 'js-div';
fragment.appendChild(div);
sections.forEach(section => {
let colors = window.getComputedStyle(section).getPropertyValue(`background-color`);
arrColors.push(colors);
});
console.log(arrColors)
function setNumberDivs(numberDiv){
for(let i= 0; i < numberDiv; i++){
container.appendChild(fragment.cloneNode(true));
arrDivs = document.querySelectorAll('.js-div');
}
arrDivs.forEach((div, index) => {
div.style.backgroundColor = arrColors[index%arrColors.length]
console.log(index)
})
console.log(divs)
}
setNumberDivs(10);
}
createDivs();
关于Javascript。存储 Section 的颜色并重新分配它们。 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59009237/