Javascript 设置顶部和左侧 CSS 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2214387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:16:02  来源:igfitidea点击:

Setting top and left CSS attributes

javascriptcoding-style

提问by Deniz Dogan

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

出于某种原因,我无法使用以下 JavaScript 设置“顶部”和“左侧”CSS 属性。

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 divgets the positionset to "absolute"but the topand leftattributes are not set!

使用 Firebug 我可以看到div获取position设置为"absolute"但未设置topleft属性!

This is for Firefox 3.6.

这适用于 Firefox 3.6。

回答by Lyubomyr Shaydariv

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

回答by Eralper

You can also use the setProperty method like below

您还可以使用 setProperty 方法,如下所示

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

回答by rinogo

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

div.style产生一个对象(CSSStyleDeclaration)。由于它是一个对象,您可以选择使用以下内容:

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

回答by serkanbasdag

We can create a new CSS class for div.

我们可以为 div 创建一个新的 CSS 类。

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