简体   繁体   English

使用JavaScript按字符串设置CSS属性

[英]Set CSS Property by string with JavaScript

So I saw this question - Get/Set CSS property values via Javascript: questions and this solution - http://www.w3schools.com/jsref/dom_obj_style.asp . 所以我看到了这个问题- 通过Javascript获取/设置CSS属性值:问题和解决方案-http: //www.w3schools.com/jsref/dom_obj_style.asp

Where my question differs is I am building a WYSIWYG editor and I want to dynamically set the properties via native javascript. 我的问题有所不同的地方是,我正在构建一个WYSIWYG编辑器,并且我想通过本机JavaScript动态设置属性。 So I was wondering if there was a way I could do something like this: 所以我想知道是否有一种方法可以做这样的事情:

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

Yeah, you can use the style name in camel case notation, or target it like you would an array name: 是的,您可以使用驼峰大小写形式的样式名称,也可以像使用数组名称一样将其作为目标:

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

Here's a fiddle with it in action: http://jsfiddle.net/m7kb2Lsa/ 这是一个正在起作用的小提琴: http : //jsfiddle.net/m7kb2Lsa/

If you want to see all of the styles you can set on an element with the correct camel casing the easiest way I've found is to type something like this in the console (assuming the element exists on the page), this will give you a full list of everything you can set: 如果要查看可以使用正确的驼峰大小设置在元素上的所有样式,我发现最简单的方法是在控制台中键入类似的内容(假设元素存在于页面上),这将为您提供您可以设置的所有内容的完整列表:

document.getElementById("myH1").style

The "proper way" is using setProperty or setPropertyValue : “正确的方法”是使用setPropertysetPropertyValue

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

They behave the same, the only difference is that setProperty accepts an optional third argument to set !important priority. 它们的行为相同,唯一的区别是setProperty接受可选的第三个参数来设置!important优先级。

However, for convenience, the 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 . 但是,为方便起见, CSSStyleDeclaration接口由部分接口扩展,以便允许使用IDL camel-case属性获取或设置受支持的CSS属性的值。

That means you can also use 这意味着您也可以使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM