1. Set the properties of the style directly some cases with this setting!important value is invalid
If the attribute has a '-' number, it is written in the form of a hump (such as textalign) if you want to preserve the-number, in the form of brackets element.style[' text-align '] = ' 100px ';
Element.style.height = ' 100px ';
2. Setting properties directly (only for certain properties, related styles are automatically recognized)
Element.setattribute (' height ', 100);
Element.setattribute (' height ', ' 100px ');
3. Set the properties of the style
Element.setattribute (' style ', ' height:100px!important ');
4. Use SetProperty If you want to set up a!important, it is recommended to set the third parameter in this way
Element.style.setProperty (' height ', ' 300px ', ' important ');
5. changing class-related methods such as JQ
Because JS gets no pseudo-elements of the CSS, you can change the style of the pseudo-element dynamically by changing the class of the pseudo-element's parent.
Element.classname = ' blue '; element.classname + = ' Blue fb ';
6. Set Csstext
Element.style.cssText = ' height:100px!important '; Element.style.cssText + = ' height:100px!important ';
7. Create a new CSS style file to introduce
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. Using Addrule, Insertrule
In the original style operation document.stylesheets[0].addrule ('. Box ', ' height:100px '); Document.stylesheets[0].insertrule ('. box {height:100px} ', 0); Or insert a new style when working with var styleel = document.createelement (' style '), styleSheet = Styleel.sheet; Stylesheet.addrule ('. Box ', ' height:100px '); Stylesheet.insertrule ('. box {height:100px} ', 0); Document.head.appendChild (Styleel);
JS set CSS styles in several ways