我有一些常见问题解答,包括问题和解答。在document
上,所有答案都被隐藏(display: none
)。
1。。在点击提问时,答案将slideDown
。
2。。在单击另一个问题时,另一个答案将slideDown
,而当前答案将slideUp
现在我需要,页面上始终显示至少一个答案(显示答案时,当前答案不会slideToggle
,我该如何实现呢?(当然使用JQuery库)
$(function () {
let answers = $('.answer');
$('.faq .ask').on('click', slideAnswer);
function slideAnswer() {
let currentAnswer = $(this).next();
currentAnswer.addClass('active');
answers.not(currentAnswer).slideUp(500).removeClass('active');
$(this).next().stop(true).slideToggle(500, function () {
if (currentAnswer.hasClass('active')) {
currentAnswer.stop(true).slideUp;
}
});
}
});
.item .ask {
background: #ccc;
}
.item .answer {
border: 1px solid #ccc;
padding: 10px;
display: none;
}
<div class="faq">
<div class="item">
<div class="ask">1. Some question №1</div>
<div class="answer">
<p>Lorem ipsum dolor sit.</p>
</div>
</div>
<div class="item">
<div class="ask">2. Some question №2</div>
<div class="answer">
<p>Lorem ipsum dolor .</p>
</div>
</div>
<div class="item">
<div class="ask">3. Some question №3</div>
<div class="answer">
<p>Lorem ipsum dolor sit .</p>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 0 :(得分:0)
尝试下面的代码
$(function () {
var answers = $('.answer');
$('.faq .ask').on('click', function(){
var currentAnswer = $(this).next('div.answer');
answers.not(currentAnswer).slideUp(500);
answers.not(currentAnswer).removeClass('active');
currentAnswer.stop(true).slideToggle(500);
currentAnswer.toggleClass('active');
});
});
答案 1 :(得分:0)
您可以简单地向上滑动所有answer
部分,而仅向下滑动当前问题的同级答案部分,如下所示:
$(document).on("click",".ask",function(){
$(".answer").slideUp("500"),$(this).siblings(".answer").slideDown("500");
})
答案 2 :(得分:0)
对于您给定的解决方案,我没有做太多改变,只是在.answer
类包含.active
类的情况下停止了代码。请检查代码段
$(function () {
let answers = $('.answer');
$('.faq .ask').on('click', slideAnswer);
function slideAnswer() {
let currentAnswer = $(this).next(),
currentAnswerState = $(this).siblings('.answer');
if (currentAnswerState.hasClass('active')) {
return true;
}
currentAnswer.addClass('active');
answers.not(currentAnswer).slideUp(500).removeClass('active');
$(this).next().stop(true).slideToggle(500, function () {
currentAnswer.stop(true).slideUp;
});
}
});
.item .ask {
background: #ccc;
}
.item .answer {
border: 1px solid #ccc;
padding: 10px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="faq">
<div class="item">
<div class="ask">1. Some question №1</div>
<div class="answer">
<p>Lorem ipsum dolor sit.</p>
</div>
</div>
<div class="item">
<div class="ask">2. Some question №2</div>
<div class="answer">
<p>Lorem ipsum dolor .</p>
</div>
</div>
<div class="item">
<div class="ask">3. Some question №3</div>
<div class="answer">
<p>Lorem ipsum dolor sit .</p>
</div>
</div>
</div>