SoFunction
Updated on 2025-04-10

Summary of how JS sets CSS style

1. Directly set the property of style. Use this setting in some cases! The important value is invalid

If the attribute has a '-' number, it is written as the camel form (such as textAlign). If you want to retain the - number, it is the form of brackets [‘text-align'] = ‘100px';

 = '100px';

2. Set attributes directly (can only be used for certain attributes, and the relevant styles will be automatically recognized)

('height', 100);
('height', '100px');

3. Set the properties of style

('style', 'height: 100px !important');

!Important's css definition has the highest priority.

4. Use setProperty. If you want to set !important, it is recommended to use this method to set the third parameter.

('height', '300px', 'important');

5. Change class   For example, JQ changes class-related methods

 = 'blue';
 += 'blue fb';

6. Set cssText

 = 'height: 100px !important';
 += 'height: 100px !important';

7. Create and introduce a new css style file

function addNewStyle(newStyle) {
      var styleElement = ('styles_js');
      if (!styleElement) {
        styleElement = ('style');
         = 'text/css';
         = 'styles_js';
        ('head')[0].appendChild(styleElement);
      }
      ((newStyle));
    }
    addNewStyle('.box {height: 100px !important;}');

8. Use addRule and insertRule

//Operate in the original style    [0].addRule('.box', 'height: 100px');
    [0].insertRule('.box {height: 100px}', 0);
    // Or when inserting a new style    var styleEl = ('style'),
      styleSheet = ;
    ('.box', 'height: 100px');
    ('.box {height: 100px}', 0);
    (styleEl);   

The above is a summary of how JS is set up CSS style introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!