1

I have this jquery code that adds a class of 'close' and slides in an element, but I want all others to close when one of them is opened. So if I click to open one of them, I want the others that are open to close, but I can't do it. HTML:

<div class="main">
<h2>Question 1?</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
  <h2>question 2</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
  <h2>Question 3?</h2>
  <div class="answer">
    <p>bla bla bla</p>
  </div>
</div>

I have this jquery:

$(document).ready(function() {
 $('.answer').hide();
 $('.main h2').toggle(
    function() {
       $(this).next('.answer').slideDown();
       $(this).addClass('close');

    },
    function() {
       $(this).next('.answer').fadeOut();
       $(this).removeClass('close');
  }
    ); // end toggle
}); // end ready
</script>

i tried adding this to the first function but on click it just slides down and then up.

$('.main .answer').not(this).slideUp();
4

1 回答 1

1
$(document).ready(function() {
    $('.answer').hide();
    $('.cat_info h2').on('click', function() {
        var state = $(this).next('.answer').is('.open');
        if (state) {
            $(this).next('.answer').removeClass('open').fadeOut();
        }else{
            $(this).next('.answer').addClass('open').slideDown()
                   .siblings('.answer').removeClass('open').slideUp();
        }
    });
});​

小提琴

仅供参考:不推荐toggle()使用这种方式

于 2012-12-27T18:02:19.350 回答