创建的div元素的随机边距不起作用

时间:2014-01-18 04:34:21

标签: javascript css html margin

问题和源代码

我正在尝试通过点击按钮在另一个<div>内创建<div>。单击该按钮后,将创建一个具有唯一ID的新内部<div>(在外部<div>内)。我有这个部分正在运行,但这里我遇到了一个问题:我希望每个内部<div>都有一个随机的margin-top

的Javascript

function pressButton() {
    number += 1;
    makeDiv(number);
};

function makeDiv(x) {
    var innerDiv = document.createElement("innerDiv" + x);
    outer.appendChild(innerDiv);
    innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + ";display:inline-block;width:48px;height:48px;background-color:#000;");
}; 

CSS:

#outer {
    position:absolute;
    white-space:nowrap;
    height:118px;
    overflow:auto;
    width:100%;
    padding:2px;
}

结果(点击按钮4次后)

<div id="outer">
    <innerDiv1 style="margin-top:15;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv1>
    <innerDiv2 style="margin-top:23;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv2>
    <innerDiv3 style="margin-top:37;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv3>
    <innerDiv4 style="margin-top:0;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv4>
</div>

结果(我从检查浏览器中的内部元素得到的结果)看起来一切正常 - 所有margin-top都是随机的,就像我想要的那样。但是,视觉效果如下:

enter image description here

如您所见,黑色内部<div>都具有相同的margin-top。我究竟做错了什么?如何使创建的<div>都具有随机margin-top s?

4 个答案:

答案 0 :(得分:3)

CSS规范要求将缺少单元的长度(除零之外)视为错误(因此被忽略)。因此,将px添加到生成的保证金编号的末尾,一切都应该正常。

答案 1 :(得分:2)

这可能是由inline-block元素使用的位置模型造成的 - 它们都是在一行的底线垂直对齐。

我建议您对此进行简化,并将position: blockfloat: left

一起使用

http://jsfiddle.net/2y5bJ/4/

我还建议您坚持使用标准元素以确保跨浏览器兼容性 - 不要创建自己的名为innerDiv1等的元素,而是使用具有唯一ID的div元素。

function makeDiv(x) {
    var innerDiv = document.createElement("div");
    outer.appendChild(div);
    innerDiv.setAttribute('id', 'innerDiv' + x);
    innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
}; 

答案 2 :(得分:2)

Live Demo

描述

这是因为您设置了display:inline-block;属性。这使得它们全部在一行中,因此它们将与具有最高innerDivx的{​​{1}}对齐。

删除margin-top属性并为其display:inline-block;。如果您想保持它们之间的差距,也请添加float:left;。不要忘记margin-left:5px;的价值需要一个单位。我想你想使用margin-top

px也不是有效的HTML代码。您应将其更改为<innerDivx>并使用<div>作为ID属性。此外,您的标签使用几乎相同的CSS样式,因此您应该将相同的标签添加到类中并添加类。

完整解决方案代码

HTML

innerDivx

的JavaScript

<button id="button1">Add box</button>
<div id="outer"></div>

CSS

var number = 0;

document.getElementById("button1").addEventListener("click", pressButton, false);

function pressButton() {
    ++number;
    makeDiv(number);
};

function makeDiv(x) {
    var innerDiv = document.createElement("div");
    outer.appendChild(innerDiv);
    innerDiv.className += " box";
    innerDiv.setAttribute("id", "innerDiv" + x);
    innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
}; 

答案 3 :(得分:0)

我认为没有名称

的标签
<innerDiv1>

这可能是原因。