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

当前回答

如果你的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");

最好的办法是创建一个函数来自己设置样式:

var setStyle = function(p_elem, p_styles)
{
    var s;
    for (s in p_styles)
    {
        p_elem.style[s] = p_styles[s];
    }
}

setStyle(myDiv, {'color': '#F00', 'backgroundColor': '#000'});
setStyle(myDiv, {'color': mycolorvar, 'backgroundColor': mybgvar});

请注意,您仍然必须使用javascript兼容的属性名称(因此使用backgroundColor)

使用ES6+,你也可以使用反引号,甚至直接从某个地方复制css:

const $div = document.createElement('div') 美元的div。innerText = 'HELLO' div.style美元。cssText = ' Background-color: rgb(26, 188, 156); 宽度:100 px; 高度:30 px; border - radius: 7 px; text-align:中心; padding-top: 10 px; 粗细:大胆的; ` document.body.append (div)美元

我只是无意中来到这里,我不明白为什么需要这么多代码来实现这一点。

使用字符串插值添加CSS代码。

Let styles = ' 字体大小:15他们; 颜色:红色; 变换:旋转(20度) document.querySelector(“*”)。样式=样式 一个

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

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

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

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

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

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