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

当前回答

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

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)

其他回答

<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>

在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");

因为字符串支持添加,你可以很容易地添加你的新样式,而不需要覆盖当前的样式:

document.getElementById("myElement").style.cssText += `
   font-size: 12px;
   left: 200px;
   top: 100px;
`;

在对象中使用CSSStyleDeclaration.setProperty()方法。样式对象的条目。 我们也可以用这个来设置CSS属性的优先级(“重要”)。 我们将使用“连字符”的CSS属性名。

Const styles = { “字体大小”:“18 px”, “粗细”:“大胆”, “背景颜色”:“lightgrey”, 颜色:“红”, "padding": "10px !important", 保证金:“20 px”, 宽度:“100px !重要”, 边框:1px纯蓝色 }; const elem = document.getElementById("my_div"); Object.entries(风格)。forEach(([prop, val]) => { Const [value, pri = ""] = val.split("!"); elem.style。setProperty(prop, value, pri); }); <div id="my_div"> Hello </div> .

请考虑使用CSS添加样式类,然后用JavaScript添加该类 classList &简单的add()函数。

style.css

.nice-style { 
fontsize : 12px; 
left: 200px;
top: 100px;
}

JavaScript脚本

const addStyle = document.getElementById("myElement"); addStyle.classList.add(“nice-style”);