问题及源码
我正在尝试创建 <div>
s在另一个<div>
单击一个按钮。单击按钮时,一个新的内部 <div>
创建(在外部 <div>
内)具有唯一 ID。我有这部分工作,但这是我遇到问题的地方:我想要每个内部 <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
就像我想要的那样是随机的。然而,视觉结果是这样的:
如你所见,黑色内层<div>
都有相同的margin-top
.我究竟做错了什么?如何创建创建的 <div>
都有随机margin-top
秒?
最佳答案
CSS 规范要求将缺少单位的长度(非零)视为错误(并因此被忽略)。因此,将 px
添加到生成的 margin 数字的末尾,一切都应该没问题。
关于javascript - 创建的 div 元素的随机边距不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21200017/