jQuery和切换图标没有正确切换

时间:2015-12-10 10:33:25

标签: javascript jquery html css

关于我在这里缺少什么的想法?我想切换点击的类,所以它是加号和减号,但目前它只是切换到减号而从不回来。

// Icon switch
$('.more').click(function() {
  var iconClass = $(this).is(':visible') ? 'less' : 'more';
  $(this).removeClass('more less').addClass(iconClass);
});
.icon {
  display: block;
  height: 18px;
  width: 18px;
  margin: 0 auto;
  display: inline-block;
  font: normal normal normal 14px/1 FontAwesome;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
}
.icon.tick:before {
  content: "\f00c";
  color: #52555a;
}
.icon.info:before {
  content: "\f05a";
  height: 23px;
  width: 33px;
}
.icon.more:before {
  content: "\f067";
  cursor: pointer;
  height: 23px;
  width: 23px;
  color: #aad042;
}
.icon.less:before {
  content: "\f068";
  cursor: pointer;
  height: 23px;
  width: 23px;
  color: #aad042;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>

1 个答案:

答案 0 :(得分:3)

您的代码存在问题,$(this).is(':visible') 始终将返回true,因为您无法点击不可见的元素(visibility:hidden除外) )。

您可以使用toggleClass()传递多个类,如下所示:

$(this).toggleClass('more less');
处理程序中的

// Icon switch
$('.more').click(function() {
  $(this).toggleClass('more less');
});
.icon {
  display: block;
  height: 18px;
  width: 18px;
  margin: 0 auto;
  display: inline-block;
  font: normal normal normal 14px/1 FontAwesome;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
}
.icon.tick:before {
  content: "\f00c";
  color: #52555a;
}
.icon.info:before {
  content: "\f05a";
  height: 23px;
  width: 33px;
}
.icon.more:before {
  content: "\f067";
  cursor: pointer;
  height: 23px;
  width: 23px;
  color: #aad042;
}
.icon.less:before {
  content: "\f068";
  cursor: pointer;
  height: 23px;
  width: 23px;
  color: #aad042;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>
<div class="icon more" data-reveal="reveal-one"></div>