我正在尝试使用嵌套for循环创建“网格”。当我检查浏览器中的元素时,他们正在接收我给他们的样式,但它们实际上并没有被定位。即使我进入并在JS加载后手动更改浏览器中的css,它们也不会改变位置。
另外,如果我使用css网格,这会更好地解决吗?
var nodeList = document.querySelectorAll('.square');
const nodeArray = [].slice.call(nodeList);
for (let i = 0; i < 3; i++){
for (let j = counter; j < (counter + 3); j++){
nodeArray[j].style.right = leftPos.toString() + "%";
nodeArray[j].style.top = topPos.toString() + "%";
nodeArray[j].style.background = 'red';
nodeArray[j].style.width = '30%';
nodeArray[j].style.height = '30%';
leftPos += 33;
}
counter += 3;
leftPos = 0;
topPos += 33;
}
}
/*there are 9 div's with class square*/
答案 0 :(得分:1)
也许你忘了在CSS上设置.square{ position: absolute; }
,
有了完整的HTML,CSS和JavaScript,我们可以提供帮助。
const
nodeList = document.querySelectorAll('.square')
let
counter = 0,
leftPos = 0,
topPos = 0
for (let i = 0; i < 3; i++){
nodeList.forEach(e =>{
e.style.right = `${leftPos}%`
e.style.top = `${topPos}%`
e.style.background = 'red'
e.style.width = '30%'
e.style.height = '30%'
leftPos += 33
})
counter += 3
leftPos = 0
topPos += 33
}
.square{
position: absolute;
color: #fff;
}
<div class="square">Foo</div>
<div class="square">Bar</div>
<div class="square">Foo</div>
<div class="square">Bar</div>
<div class="square">Foo</div>
<div class="square">Bar</div>
<div class="square">Foo</div>
您可以使用forEach而不是创建另一个数组const nodeArray = [].slice.call(nodeList);