我有以下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
我认为这是一种非常简单的解决上述所有问题的方法:
const elm = document.getElementById("myElement")
const allMyStyle = [
{ prop: "position", value: "fixed" },
{ prop: "boxSizing", value: "border-box" },
{ prop: "opacity", value: 0.9 },
{ prop: "zIndex", value: 1000 },
];
allMyStyle.forEach(({ prop, value }) => {
elm.style[prop] = value;
});
在对象中使用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> .
在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");