Home >Web Front-end >JS Tutorial >How to set css in native js
Method: 1. Use the style "style.property=value" statement to set; 2. Use the "setAttribute(property, value)" statement to set; 3. Use the "setProperty(property, value)" statement to set; 4. Use the "style.cssText='property:value'" statement to set.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Use JS to dynamically set CSS styles (set to inline styles). Common ones include the following
1. Directly set the style attribute Use this setting in some cases! The important value is invalid
If the attribute has a '-' sign, write it in camel case (such as textAlign). If you want to retain the - sign, write it in the form of square brackets element. style['text-align'] = '100px';
element.style.height = '100px';
2. Set attributes directly (can only be used for certain attributes, related styles will be automatically recognized)
element.setAttribute('height', 100); element.setAttribute('height', '100px');
3. Use setProperty If you want to set !important, it is recommended to use this method to set the third parameter
element.style.setProperty('height', '300px', 'important');
4. Set cssText
element.style.cssText = 'height: 100px !important'; // 覆盖其他行内样式 element.style.cssText += 'height: 100px !important'; // 追加行内样式
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to set css in native js. For more information, please follow other related articles on the PHP Chinese website!