我有以下JavaScript变量:

var fontsize = "12px"
var left= "200px"
var top= "100px"

我知道我可以像这样迭代地将它们设置为我的元素:

document.getElementById("myElement").style.top=top
document.getElementById("myElement").style.left=left

有没有可能把它们都放在一起,就像这样?

document.getElementById("myElement").style = allMyStyle 

当前回答

@Mircea:在一条语句中为一个元素设置多种样式非常容易。 它不会影响现有的属性,并避免了循环或插件的复杂性。

document.getElementById("demo").setAttribute(
   "style", "font-size: 100px; font-style: italic; color:#ff0000;");

注意:如果以后使用此方法添加或更改样式属性,之前使用'setAttribute'设置的属性将被擦除。

其他回答

<button onclick="hello()">Click!</button>

<p id="demo" style="background: black; color: aliceblue;">
  hello!!!
</p>

<script>
  function hello()
  {
    (document.getElementById("demo").style.cssText =
      "font-size: 40px; background: #f00; text-align: center;")
  }
</script>

@Mircea:在一条语句中为一个元素设置多种样式非常容易。 它不会影响现有的属性,并避免了循环或插件的复杂性。

document.getElementById("demo").setAttribute(
   "style", "font-size: 100px; font-style: italic; color:#ff0000;");

注意:如果以后使用此方法添加或更改样式属性,之前使用'setAttribute'设置的属性将被擦除。

var styles = {
    "background-color": "lightgray",
    "width": "500px",
    "height": "300px"
};

/

var obj = document.getElementById("container");
Object.assign(obj.style, styles);

下面的innerHtml是否有效

var styleElement = win.document.createElement("STYLE"); styleElement。innerHTML = "#notEditableVatDisplay {display:inline-flex} #editableVatInput,.print-section, i.a a.fa-sort. "点击排序{显示:none !重要}";

使用纯Javascript,你不能一次设置所有的样式;您需要为它们每个使用单行。

但是,您不必重复document.getElementById(…).style。一遍又一遍地编码;创建一个对象变量来引用它,你会让你的代码更易于阅读:

var obj=document.getElementById("myElement").style;
obj.top=top;
obj.left=left;

…等。比您的示例更容易阅读(坦白地说,和jQuery一样容易阅读)。

(如果Javascript设计正确,你也可以使用with关键字,但最好不要使用它,因为它会导致一些讨厌的名称空间问题)