当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js和jquery设置css样式的几种方法

js和jquery设置css样式的几种方法

2020年04月12日  | 移动技术网IT编程  | 我要评论

一、js设置样式的方法

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

element.style.height = '50px';

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

  element.setattribute('height',50);
  element.setattribute('height',50px');

3. 设置style的属性

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

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

element.style.setproperty('height', '300px', 'important');

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

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

element.classname = 'blue';
element.classname += 'blue fb';

6. 设置csstext

element.style.csstext = 'height: 100px !important';
element.style.csstext += 'height: 100px !important';


二、jquery设置样式的几种方法

1、设置所有匹配元素的指定 css 属性 不支持属性名称简写(如border和background)

$(selector).css(name,value)

2、使用函数来设置 css 属性
$(selector).css(name,function(index,value))

$("button").click(function(){
   $("p").css("color",function(){return "red";}); 
});
name:必需。规定 css 属性的名称。该参数可包含任何 css 属性,比如 "color";
function(index,value):规定返回 css 属性新值的函数。index - 可选。接受选择器的 index 位置;value - 可选。接受 css 属性的当前值
3、设置多个 css 属性/值对

$(selector).css({property:value, property:value, ...})
$("p").css({"color":"white","background-color":"#98bf21", "font-family":"arial", "font-size":"20px","padding":"5px"});

文章转自:https://www.cnblogs.com/nature-wind8/p/10423671.html

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网