我在一个正在研究的网站上有手风琴。它有一个烦人的错误,我无法弄清楚。
如果单击箭头,手风琴将正确打开和关闭。如果你点击标题,手风琴将会打开但是当你试图关闭它时它会弹回。
标题和箭头都在同一个锚中,所以我理解为什么会发生这种情况。
代码是:
<div class="accordion">
<div class="accordion-section">
<div class="tab">
<a class="accordion-title accordion-section-button l2" href="#accordion-205">
<h3>How do you differ from estate agents?</h3>
</a>
<div id="accordion-205" class="accordion-section-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc mattis ante eget quam volutpat, ac pulvinar massa ornare.</p>
</div>
</div>
<div class="tab">
<a class="accordion-title accordion-section-button l2" href="#accordion-204">
<h3>Why would an estate agent prefer speaking or dealing with yourself?</h3>
</a>
<div id="accordion-204" class="accordion-section-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc mattis ante eget quam volutpat, ac pulvinar massa ornare.</p>
</div>
</div>
</div>
</div>
$(document).ready(function() {
function close_accordion_section() {
$('.accordion .accordion-section-button').removeClass('active');
$('.accordion .accordion-section-content').slideUp(300).removeClass('open');
}
$('.accordion-section-button').click(function(e) {
// Grab current anchor value
var currentAttrValue = $(this).attr('href');
if($(e.target).is('.active')) {
close_accordion_section();
}else {
close_accordion_section();
// Add active class to section title
$(this).addClass('active');
// Open up the hidden content panel
$('.accordion ' + currentAttrValue).slideDown(300).addClass('open');
}
e.preventDefault();
});
});
答案 0 :(得分:1)
主要问题是这一行:
if($(e.target).is('.active')) {
当您点击<h3>
时,元素e.target
将是<h3>
而不是<a>
。而是尝试这样的事情:
if($(this).is('.active')) {
请注意,现在这与您进一步向下添加该类的行保持一致。
答案 1 :(得分:0)
如果您愿意,可以将所有内容减少到:
$(document).ready(function() {
$('.accordion-section-button').click(function(e) {
close_accordion_section();
$(this).toggleClass('active');
$('.accordion ' + this.attributes.href.value)[(this.classList.contains('active')) ? 'slideDown' : 'slideUp'](300)
.toggleClass('open');
e.preventDefault();
});
});