Setting top and left CSS attributes

懵懂的女人 提交于 2019-12-18 10:58:49

问题


For some reason I'm unable to set the "top" and "left" CSS attributes using the following JavaScript.

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

Using Firebug I can see that the div gets the position set to "absolute" but the top and left attributes are not set!

This is for Firefox 3.6.


回答1:


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



回答2:


You can also use the setProperty method like below

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



回答3:


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";



回答4:


We can create a new CSS class for div.

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


来源:https://stackoverflow.com/questions/2214387/setting-top-and-left-css-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!