将变量中指定的CSS属性以外的属性赋予样式。
方法一:使用基本的CSS语法和JavaScript
const styleFromVariable = {
background: "red",
color: "white",
fontSize: "20px",
padding: "10px"
};
const exceptFor = ["background", "fontSize"];
const element = document.getElementById("myElement");
for (let prop in styleFromVariable) {
if (!exceptFor.includes(prop)) {
element.style[prop] = styleFromVariable[prop];
}
}
方法二:使用Lodash库
const styleFromVariable = {
background: "red",
color: "white",
fontSize: "20px",
padding: "10px"
};
const exceptFor = ["background", "fontSize"];
const element = document.getElementById("myElement");
_.forEach(_.omit(styleFromVariable, exceptFor), (value, prop) => {
element.style[prop] = value;
});