我有以下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(节点);
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代码: ***
&lt; div id =“pos”&gt;&lt; / div&gt;
第一个元素正确定位,0px顶部和30px,但第二个和第三个没有标记,我试图使用显示作为内联但只设置在同一行但左侧定位没有设置。结果是 as shown in this picture
答案 0 :(得分:2)
添加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
答案 1 :(得分:0)
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'; //added
div.style.marginLeft = '1%'; //added
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);
}
将每个div显示为内联块并为它们提供一个余量 Check this