JS设置CSS样式的几种方式(js设置!important)

时间:2025-01-22 12:10:50

 

1. 直接设置style的属性  某些情况用这个设置 !important值无效

如果属性有'-'号,就写成驼峰的形式(如textAlign)  如果想保留 - 号,就中括号的形式  ['text-align'] = '100px';

 = '100px';

2. 直接设置属性(只能用于某些属性,相关样式会自动识别)

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

3. 设置style的属性

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

4. 使用setProperty  如果要设置!important,推荐用这种方法设置第三个参数,属性名不用驼峰写法

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

5. 改变class   比如JQ的更改class相关方法

因JS获取不到css的伪元素,所以可以通过改变伪元素父级的class来动态更改伪元素的样式

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

6. 设置cssText

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

7. 创建引入新的css样式文件

        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. 使用addRule、insertRule

// 在原有样式操作
        [0].addRule('.box', 'height: 100px');
        [0].insertRule('.box {height: 100px}', 0);

        // 或者插入新样式时操作 var styleEl = ('style'), styleSheet = ; ('.box', 'height: 100px'); ('.box {height: 100px}', 0); (styleEl); 

用JS来动态设置CSS样式,常见的有以下几种

 

1. 直接设置style的属性  某些情况用这个设置 !important值无效

如果属性有'-'号,就写成驼峰的形式(如textAlign)  如果想保留 - 号,就中括号的形式  ['text-align'] = '100px';

 = '100px';

2. 直接设置属性(只能用于某些属性,相关样式会自动识别)

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

3. 设置style的属性

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

4. 使用setProperty  如果要设置!important,推荐用这种方法设置第三个参数

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

5. 改变class   比如JQ的更改class相关方法

因JS获取不到css的伪元素,所以可以通过改变伪元素父级的class来动态更改伪元素的样式

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

6. 设置cssText

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

7. 创建引入新的css样式文件

        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. 使用addRule、insertRule

        // 在原有样式操作
        [0].addRule('.box', 'height: 100px');
        [0].insertRule('.box {height: 100px}', 0);

        // 或者插入新样式时操作 var styleEl = ('style'), styleSheet = ; ('.box', 'height: 100px'); ('.box {height: 100px}', 0); (styleEl);