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

当前回答

使用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)美元

其他回答

不要认为这是可能的。

但是你可以用样式定义创建一个对象,然后循环遍历它们。

var allMyStyle = {
  fontsize: '12px',
  left: '200px',
  top: '100px'
};

for (i in allMyStyle)
  document.getElementById("myElement").style[i] = allMyStyle[i];

为了进一步开发,为它创建一个函数:

function setStyles(element, styles) {
  for (i in styles)
    element.style[i] = styles[i];
}

setStyles(document.getElementById("myElement"), allMyStyle);

您可以在css文件中拥有单独的类,然后将类名分配给元素

或者你可以循环样式的属性为-

var css = { "font-size": "12px", "left": "200px", "top": "100px" };

for(var prop in css) {
  document.getElementById("myId").style[prop] = css[prop];
}
<button onclick="hello()">Click!</button>

<p id="demo" style="background: black; color: aliceblue;">
  hello!!!
</p>

<script>
  function hello()
  {
    (document.getElementById("demo").style.cssText =
      "font-size: 40px; background: #f00; text-align: center;")
  }
</script>

@Mircea:在一条语句中为一个元素设置多种样式非常容易。 它不会影响现有的属性,并避免了循环或插件的复杂性。

document.getElementById("demo").setAttribute(
   "style", "font-size: 100px; font-style: italic; color:#ff0000;");

注意:如果以后使用此方法添加或更改样式属性,之前使用'setAttribute'设置的属性将被擦除。

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

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)