设置顶部和左边的 CSS 属性

由于某种原因,我无法使用以下 JavaScript 设置“ top”和“ left”CSS 属性。

var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = 200;
div.style.left = 200;
document.body.appendChild(div);

通过使用 Firebug,我可以看到 divposition设置为 "absolute",但是没有设置 topleft属性!

这是针对 Firefox 3.6的。

142239 次浏览

Your problem is that the top and left properties require a unit of measure, not just a bare number:

div.style.top = "200px";
div.style.left = "200px";

You can also use the setProperty method like below

document.getElementById('divName').style.setProperty("top", "100px");

div.style yields an object (CSSStyleDeclaration). Since it's an object, you can alternatively use the following:

div.style["top"] = "200px";
div.style["left"] = "200px";

This is useful, for example, if you need to access a "variable" property:

div.style[prop] = "200px";

We can create a new CSS class for div.

 .div {
position: absolute;
left: 150px;
width: 200px;
height: 120px;
}