gpt4 book ai didi

javascript - 设置动态变化的元素的左侧位置(在循环中)

转载 作者:行者123 更新时间:2023-11-30 16:32:02 30 4
gpt4 key购买 nike

我有以下 JavaScript 代码。 ***

var pos = document.getElementById('pos');
pos.style.position = 'relative';
pos.style.width = '100%';
pos.style.height = '100%';
pos.style.background = 'gray';
for(i=1;i<4;i++)
{
var div = document.createElement('div');
var node = document.createTextNode("This is new.");
div.appendChild(node);
var j = i-1;
var f = Math.round(250/(i+1));
var d = Math.round(250/i);
var col = 'rgb('+f+','+140+','+d+')';
div.style.background = col;
div.style.width = '200px';
div.style.height = '300px';
div.style.position = 'relative';
div.style.top = '0px';
div.style.border = 'solid';
div.style.borderColor = 'green';
div.style.borderWidth = '2px';
left = Math.floor((j*200)+30+30);
left = left+'px';
div.style.left = '30px';
pos.appendChild(div);
}


HTML代码: ***

<div id = "pos"></div>


第一个元素的位置正确,顶部为 0px,左侧为 30px,但是第二个和第三个元素偏离了标记,我尝试将显示用作内联,但只将它们设置在同一行但未设置左侧定位。结果是 as shown in this picture

But I would like it to appear as:

最佳答案

添加一个display:inline-block,并在动态创建的元素上放置一些margin-right:10px

这里是修改后的代码:

var pos = document.getElementById('pos');
pos.style.position = 'relative';
pos.style.width = '100%';
pos.style.height = '100%';
pos.style.background = 'gray';
for(i=1;i<4;i++)
{
var div = document.createElement('div');
var node = document.createTextNode("This is new.");
div.appendChild(node);
var j = i-1;
var f = Math.round(250/(i+1));
var d = Math.round(250/i);
var col = 'rgb('+f+','+140+','+d+')';
div.style.background = col;
div.style.width = '200px';
div.style.height = '300px';
div.style.position = 'relative';
div.style.display="inline-block"; //add this line
div.style.marginRight="10px"; //add this line
div.style.top = '0px';
div.style.border = 'solid';
div.style.borderColor = 'green';
div.style.borderWidth = '2px';
left = Math.floor((j*200)+30+30);
left = left+'px';
div.style.left = '30px';
pos.appendChild(div);
}

检查 fiddle

关于javascript - 设置动态变化的元素的左侧位置(在循环中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33184015/

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