jquery中toggleClass方法用于样式切换

实例

对设置和移除所有 <p> 元素的 "main" 类进行切换:

$("button").click(function(){
  $("p").toggleClass("main");
});

定义和用法

toggleClass() 对设置或移除被选元素的一个或多个类进行切换。

该方法检查每个元素中指定的类。如果不存在则添加类,如果已设置则删除之。这就是所谓的切换效果。

不过,通过使用 "switch" 参数,您能够规定只删除或只添加类。

语法

$(selector).toggleClass(class,switch)
参数描述
class

必需。规定添加或移除 class 的指定元素。

如需规定若干 class,请使用空格来分隔类名。

switch 可选。布尔值。规定是否添加或移除 class。

使用函数来切换类

$(selector).toggleClass(function(index,class),switch)

亲自试一试

参数描述
function(index,class)

必需。规定返回需要添加或删除的一个或多个类名的函数。

  • index - 可选。接受选择器的 index 位置。
  • class - 可选。接受选择器的当前的类。
switch 可选。布尔值。规定是否添加(true)或移除(false)类。

 

 

实例:

js代码:

$(".play").click(function(){
  $(this).toggleClass("play");
})

 

 

html页面:

<div class="time-panel-btn play" > </div>

该div有两个class名,分别为time-panel-btn和play。

 

css样式:

.time-panel-btn.play {
background: url(http://webmap0.map.bdstatic.com/newheatmap/static/index/images/time-btn-play_22fead8.png?__sprite) no-repeat 0 0;
}

.time-panel-btn {
background: url(http://webmap0.map.bdstatic.com/newheatmap/static/index/images/time-btn-pause_8c55183.png?__sprite) no-repeat 0 0;
width: 33px;
height: 33px;
float: right;
cursor: pointer;
}

 

posted @ 2015-12-07 09:22  i日出  阅读(3414)  评论(0编辑  收藏  举报