如何在JavaScript中设置多个CSS样式? [英] How can I set multiple CSS styles in JavaScript?

查看:246
本文介绍了如何在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.

这篇关于如何在JavaScript中设置多个CSS样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆