我试图使用slidetoggle
和slideDown
显示/隐藏我的div元素。它的工作非常好。
现在我要做的是,我想要addClass
' visible-divs'只有可见的div和隐藏的removeClass
。
问题是,该类已成功添加,但在slides up
隐藏它时它不会删除该类。我做错了什么?
$(".OffersContainer > div:gt(0)").hide();
$(".OffersContainer > span").click(function() {
this.clickCount = (this.clickCount || 0) + 1
var command = this.clickCount % 3 === 0 ? 'slideToggle' : 'slideDown';
$(this).siblings(this.clickCount % 3 === 1 ? "div:lt(3)" : "div:gt(0)")[command]();
$('.pan-box').filter(':visible').addClass("visible-divs");
$('.pan-box').filter(':hidden').removeClass("visible-divs");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OffersContainer">
<div class='pan-box'>A</div>
<div class='pan-box'>B</div>
<div class='pan-box'>C</div>
<div class='pan-box'>D</div>
<div class='pan-box'>E</div>
<span>Show more</span>
</div>
&#13;
答案 0 :(得分:4)
为此,您需要在动画完成后选择:visible
/ :hidden
元素。为此,请使用回调函数参数:
$(".OffersContainer > span").click(function() {
this.clickCount = (this.clickCount || 0) + 1
var command = this.clickCount % 3 === 0 ? 'slideToggle' : 'slideDown';
$(this).siblings(this.clickCount % 3 === 1 ? "div:lt(3)" : "div:gt(0)")[command](function() {
$('.pan-box').filter(':visible').addClass("visible-divs");
$('.pan-box').filter(':hidden').removeClass("visible-divs");
});
});
顺便说一句,更改隐藏元素上的类有什么意义?根据定义,效果将不会被看到。如果您想知道隐藏哪些元素,您可以单独使用:hidden
选择器
答案 1 :(得分:0)
如果您不想等待动画完成,因为您已经知道要隐藏或显示哪些选项,而不是使用此代码:
$(".OffersContainer > div:gt(0)").hide();
$(".OffersContainer > span").click(function() {
this.clickCount = (this.clickCount || 0) + 1
var command = this.clickCount % 3 === 0 ? 'slideToggle' : 'slideDown';
$(this).siblings(this.clickCount % 3 === 1 ? "div:lt(3)" : "div:gt(0)")[command]();
console.log(this.clickCount % 3 * 3 - 1);
$('.pan-box:lt(' + (this.clickCount % 3 * 3) + ')').addClass("visible-divs");
$('.pan-box:gt(' + (this.clickCount % 3 * 3) + ')').removeClass("visible-divs");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OffersContainer">
<div class='pan-box'>A</div>
<div class='pan-box'>B</div>
<div class='pan-box'>C</div>
<div class='pan-box'>D</div>
<div class='pan-box'>E</div>
<span>Show more</span>
</div>
同样在 JSFiddle playground 。