gpt4 book ai didi

javascript - 使用 JavaScript 定位元素时 Div 对样式无响应

转载 作者:行者123 更新时间:2023-11-28 15:02:28 25 4
gpt4 key购买 nike

我正在尝试使用嵌套的 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*/

最佳答案

也许你只是忘记设置 .square{ position: absolute; 在 CSS 上,借助完整的 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);

关于javascript - 使用 JavaScript 定位元素时 Div 对样式无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49927891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com