我有以下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 

当前回答

实现这一目标的不同方法:

1. document.getElementById("ID").style.cssText = "display:block; position:relative; font-size:50px";
2. var styles = {"display":"block"; "position":"relative"; "font-size":"50px"};
 
   var obj = document.getElementById("ID");
   Object.assign(obj.style, styles);

3. var obj = document.getElementById("ID");
obj.setAttribute("style", "display:block; position:relative; font-size:50px");

希望这对RDaksh有帮助

其他回答

对我来说最简单的方法就是使用字符串/模板字面值:

elementName.style.cssText = `
                                width:80%;
                                margin: 2vh auto;
                                background-color: rgba(5,5,5,0.9);
                                box-shadow: 15px 15px 200px black; `;

伟大的选择,因为你可以使用多行字符串,使生活更容易。

查看字符串/模板文字在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

请考虑使用CSS添加样式类,然后用JavaScript添加该类 classList &简单的add()函数。

style.css

.nice-style { 
fontsize : 12px; 
left: 200px;
top: 100px;
}

JavaScript脚本

const addStyle = document.getElementById("myElement"); addStyle.classList.add(“nice-style”);

如果你的CSS值为字符串,并且没有为元素设置其他CSS(或者你不关心覆盖),请使用cssText属性:

document.getElementById("myElement").style.cssText = "display: block; position: absolute";

你也可以使用模板文字来获得更简单、更可读的多行css语法:

document.getElementById("myElement").style.cssText = `
  display: block; 
  position: absolute;
`;

这在某种意义上是好的,因为它避免了每次更改属性时重新绘制元素(以某种方式“一次性”更改所有属性)。

另一方面,你必须先构建字符串。

在Javascript中设置多个css样式属性

document.getElementById("yourElement").style.cssText = cssString;

or

document.getElementById("yourElement").setAttribute("style",cssString);

例子:

document
.getElementById("demo")
.style
.cssText = "margin-left:100px;background-color:red";

document
.getElementById("demo")
.setAttribute("style","margin-left:100px; background-color:red");

因为字符串支持添加,你可以很容易地添加你的新样式,而不需要覆盖当前的样式:

document.getElementById("myElement").style.cssText += `
   font-size: 12px;
   left: 200px;
   top: 100px;
`;