给class类加css样式,addClass()

addClass()

为每个匹配的元素添加指定的样式类名.addClass(className)

className。类型: String。一个或多个,以空格分隔的class类名。

jQuery3.3版本增加

.addClass(className)

className。类型: Array。要添加到每个匹配元素的class属性的类的数组。

.addClass(function)

function。类型: Function(Integer index,String currentClassName)=>String。这个函数返回一个或更多用空格隔开的要增加的样式名。接收元素在集合中的索引位置以及现有的类名称作为参数。在函数内,this引用集合中的当前元素。

值得注意的是这个方法不会替换一个样式类名。它只是简单的添加一个样式类名到元素上。注意:jQuery的版本1.12 / 2.2之前,.addClass()方法操纵的className 特性所选择的元素,而不是的class 属性。更改属性后,将由浏览器相应地更新属性。这种行为的暗示是,该方法仅适用于具有HTML DOM语义的文档(例如,非纯XML文档)。从jQuery 1.12 / 2.2开始,此行为已更改,以改善对XML文档(包括SVG)的支持。从该版本开始,将使用class 属性。因此,.addClass()可以在XML或SVG文档上使用。

对所有匹配的元素可以一次添加多个用空格隔开的样式类名,像这样:$("p").addClass("myClass yourClass");

这个方法通常和.removeClass()一起使用,用来切换元素的样式,像这样:$("p").removeClass("myClass noClass").addClass("yourClass");

这里,myClass和noClass样式名在所有段落上被移除,然后yourClass被添加。

自 jQuery 1.4开始,.addClass()方法允许我们通过传递一个用来设置样式类名的函数。$("ul li:last").addClass(function(index) {

return "item-" + index;

});

给定一个有2个

元素的无序列表,此示例将类“item-0”添加到第一个,并将“item-1”添加到第二个。。

例子

在匹配的元素上加上'selected'样式。

p { margin: 8px; font-size:16px; }

.selected { color:blue; }

.highlight { background:yellow; }

Hello

and

Goodbye

$("p").last().addClass("selected");

Hello

and

Goodbye

在匹配的元素上加上'selected'和'highlight'样式。

p { margin: 8px; font-size:16px; }

.selected { color:red; }

.highlight { background:yellow; }

Hello

and

Goodbye

$("p:last").addClass("selected highlight");

Hello

and

Goodbye

将类别“selected”和“highlight”添加到匹配的元素(3.3+语法)。

p { margin: 8px; font-size:16px; }

.selected { color:red; }

.highlight { background:yellow; }

Hello

and

Goodbye

$("p:last").addClass([ "selected", "highlight" ]);

Hello

and

Goodbye

传递一个函数以.addClass()将“green”类添加到已经具有“red”类的div中。

div { background: white; }

.red { background: red; }

.red.green { background: green; }

This div should be white
This div will be green because it now has the "green" and "red" classes.

It would be red if the addClass function failed.

This div should be white

There are zero green divs

$("div").addClass(function(index, currentClass) {

var addedClass;

if ( currentClass === "red" ) {

addedClass = "green";

$("p").text("There is one green div");

}

return addedClass;

});

This div should be white

This div will be green because it now has the "green" and "red" classes. It would be red if the addClass function failed.

This div should be white

There are zero green divs

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值