我只需要一个简单的手风琴脚本,并且不想处理jQuery手风琴小部件的膨胀并在网上找到这个。它工作正常,但我想知道我是否可以在打开的手风琴块中添加类似active
的类。
这是脚本:
$(document).ready(function($) {
$('#accordion').find('.accordion-toggle').click(function() {
//Expand or collapse this panel
$(this).next().slideToggle('fast');
//Hide the other panels
$(".accordion-content").not($(this).next()).slideUp('fast');
});
});
.accordion-toggle {
cursor: pointer;
}
.accordion-content {
display: none;
}
.accordion-content.default {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="accordion">
<h4 class="accordion-toggle">Accordion 1</h4>
<div class="accordion-content default">
<p>Cras malesuada ultrices augue molestie risus.</p>
</div>
<h4 class="accordion-toggle">Accordion 2</h4>
<div class="accordion-content">
<p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
</div>
<h4 class="accordion-toggle">Accordion 3</h4>
<div class="accordion-content">
<p>Vivamus facilisisnibh scelerisque laoreet.</p>
</div>
</div>
答案 0 :(得分:1)
当然,就像在这段代码中一样(使用.addClass
方法)
$(document).ready(function($) {
$('#accordion').find('.accordion-toggle').click(function() {
//Expand or collapse this panel
$(this).next().addClass('active').slideToggle('fast');
//Hide the other panels
$(".accordion-content").not($(this).next()).removeClass('active').slideUp('fast');
});
});
.accordion-toggle {
cursor: pointer;
}
.accordion-content {
display: none;
}
.accordion-content.default {
display: block;
}
/* just to demo the .active class */
.active {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="accordion">
<h4 class="accordion-toggle">Accordion 1</h4>
<div class="accordion-content default active">
<p>Cras malesuada ultrices augue molestie risus.</p>
</div>
<h4 class="accordion-toggle">Accordion 2</h4>
<div class="accordion-content">
<p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
</div>
<h4 class="accordion-toggle">Accordion 3</h4>
<div class="accordion-content">
<p>Vivamus facilisisnibh scelerisque laoreet.</p>
</div>
</div>
我使用.active
向background: red
设置样式以显示.active