如何在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.