用 JavaScript 按字符串设置 CSS 属性

Set CSS Property by string with JavaScript

所以我看到了这个问题 - Get/Set CSS property values via Javascript: questions and this solution - http://www.w3schools.com/jsref/dom_obj_style.asp

我的问题不同之处在于我正在构建一个 WYSIWYG 编辑器,我想通过原生 javascript 动态设置属性。所以我想知道是否有办法可以做这样的事情:

document.getElementById("myH1").style.property("color") = "red";

是的,您可以使用驼峰式命名法的样式名称,或者像数组名称一样定位它:

document.getElementById("myH1").style.color = "red";
document.getElementById("myH1").style["color"] = "red";

这是一个 fiddle 的实际效果:http://jsfiddle.net/m7kb2Lsa/

如果您想查看可以在具有正确驼峰式大小写的元素上设置的所有样式,我发现最简单的方法是在控制台中键入类似这样的内容(假设该元素存在于页面上) ,这将为您提供您可以设置的所有内容的完整列表:

document.getElementById("myH1").style

"proper way" 正在使用 setProperty or setPropertyValue:

element.style.setProperty("background-color", "red");
element.style.setPropertyValue("background-color", "red");

它们的行为相同,唯一的区别是 setProperty 接受可选的第三个参数来设置 !important 优先级。

不过,为了方便起见,CSSStyleDeclaration interface is extended by partial interfaces in order to allow to get or set the values of supported CSS properties using IDL camel-case attributes.

这意味着您也可以使用

element.style.backgroundColor = "red";
element.style["backgroundColor"] = "red";