如何在JavaScript中设置多个CSS样式?

如何在JavaScript中设置多个CSS样式?

问题描述:

我有以下JavaScript变量:

I have the following JavaScript variables:

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

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

I know that I can set them to my element iteratively like this:

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

是否可以同时将它们全部设置在一起这样吗?

Is it possible to set them all together at once, something like this?

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


如果您将CSS值作为字符串,并且没有为元素设置其他CSS(或者您不关心覆盖),使用 cssText property

If you have the CSS values as string and there is no other CSS already set for the element (or you don't care about overwriting), make use of the cssText property:

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

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

This is good in a sense as it avoids repainting the element every time you change a property (you change them all "at once" somehow).

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

On the other side, you would have to build the string first.