jQuery可扩展和可折叠的div

时间:2013-12-20 23:53:38

标签: jquery

我在创建的常见问题解答页面上有一些扩展和折叠div的问题。当用户单击一个问题时,它需要折叠所有其他答案div并仅展开单击(问题)div的答案。我现在想通了 - 除了一旦用户点击了页面上的所有div并且它们全部展开然后折叠之后,它再用2次鼠标点击再次重新打开它们而不只是一次。

jQuery的:

$(document).ready(function() {
$('.answer').hide(); // hide the answer divs first

$('#content .question').click().toggle(
    function() {
         $('.answer').hide(); //hide all other divs when clicked
         $('#content .question').removeClass('close'); // as well as remove the 'expanded' icon
         $(this).next('.answer').slideDown();  //slidedown the appropriate div
         $(this).addClass('close'); //as well as insert the 'expanded' icon
         },
         function() {
            $(this).next('.answer').slideUp(); // hide the selected div
            $(this).removeClass('close'); // as well as remove the 'expanded' icon
            }
        );
    });

CSS:

#content {width: 1310px; height: 350px;}
#col_1 {width: 380px; height: 350px; margin: 20px; padding: 5px;}
.question {color: #64AA01; background-image:  url(images/open_div.jpg); cursor: pointer; background-repeat: no-repeat; padding-left: 15px;}
.close {background-image:  url(images/close_div.jpg);}
.answer {margin-left: 16px;}

HTML:

<div id="content">

<div id="col_1">

<div class="question">
<div align="justify">Q: This is question 1.</div>
</div>

<div class="answer" style = "width: 360px;">
<div align="justify">A: This answer is the answer to question 1.</div>
</div><br><br>

<div class="question">Q: This is question 2.</div>
<div class="answer" style = "width: 360px;">
<div align="justify">A: This answer is the answer to question 2.</div>
</div><br><br>

<div class="question">
<div align="justify">Q: This is question 3.</div>
</div>

<div class="answer" style = "width: 360px;">
<div align="justify">A: This answer is the answer to question 3.</div>
</div>

</div>

</div>

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这可能是您正在寻找的:

jsFiddle Demo

$('.answer').hide(); // hide the answer divs first

$('.question').click(function() {
    $('.answer').slideUp();
    $(this).next('.answer').slideDown();
});

这是一个修改,允许您点击问题之外的任何地方,所有答案将重新关闭。请注意使用e.stopPropagation()来阻止始终的答案被重新隐藏。

jsFiddle Demo 2

$('.answer').hide(); // hide the answer divs first

$('.question').click(function(e) {
    $('.answer').slideUp();
    $(this).next('.answer').slideDown();
    e.stopPropagation();
});

$(document).click(function(){
    $('.answer').slideUp();
});

答案 1 :(得分:0)

这是一个Plunker示例。

在这种情况下,您无需使用切换:

 $('#content .question').click(function() {
     $('#content .question').removeClass('close'); // as well as remove the 'expanded' icon
     $('#content .answer').slideUp();
     $(this).next('.answer').slideDown(); //slidedown the appropriate div
     $(this).addClass('close'); //as well as insert the 'expanded' icon
    });
  });

另外,我将此添加到css中,以便您的答案默认为不显示:

.answer {
   display: none;
}