Summary of common methods for setting CSS styles dynamically using JS (recommended), jscss
Use JS to dynamically set CSS styles. The following are common examples:
1. directly set the style attribute. In some cases, use this setting! The important value is invalid.
If the attribute has a '-', it is written as a camper (for example, textAlign). If you want to retain a-number, it is element in brackets. style ['text-align '] = '100px ';
element.style.height = '100px';
2. Set attributes directly (only for certain attributes, and relevant styles will be automatically recognized)
element.setAttribute('height', 100);element.setAttribute('height', '100px');
3. Set the style attributes
element.setAttribute('style', 'height: 100px !important');
4. Use setProperty if you want to set it! Important. We recommend that you use this method to set the third parameter.
element.style.setProperty('height', '300px', 'important');
5. Change the class-related methods such as JQ
Because JavaScript cannot obtain the pseudo elements of css, You can dynamically change the style of the pseudo element by changing the class of the parent level of the pseudo element.
element.className = 'blue';element.className += 'blue fb';
6. Set cssText
element.style.cssText = 'height: 100px !important';element.style.cssText += 'height: 100px !important';
7. Create and introduce a new css style File
function addNewStyle(newStyle) {var styleElement = document.getElementById('styles_js');if (!styleElement) {styleElement = document.createElement('style');styleElement.type = 'text/css';styleElement.id = 'styles_js';document.getElementsByTagName('head')[0].appendChild(styleElement);}styleElement.appendChild(document.createTextNode(newStyle));}addNewStyle('.box {height: 100px !important;}');
8. Use addRule and insertRule
// Operate document in the original style. styleSheets [0]. addRule ('. box ', 'height: 100px'); document. styleSheets [0]. insertRule ('. box {height: 100px} ', 0); // you can specify var styleEl = document when inserting a new style. createElement ('style'), styleSheet = styleEl. sheet; styleSheet. addRule ('. box ', 'height: 100px'); styleSheet. insertRule ('. box {height: 100px} ', 0); document. head. appendChild (styleEl );
The above is a summary of common methods for setting CSS styles dynamically using JS. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!