单击另一个div时关闭当前切换div

时间:2013-10-15 21:02:33

标签: javascript jquery html css

现在,我有一个基本的幻灯片和切换脚本,现在有了帮助,点击后会添加一个背景。但是,我想这样,当点击另一个“点击我”时,它会关闭该div并打开新的div。从本质上讲,我不希望切换的div不断相互重叠。

http://jsfiddle.net/schermerb/rAMQT/6/

<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>
<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>
<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>
<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>

.toggleBtn {
    font:14px noral Futura, sans-serif;
    color:black;
    margin:50px;
    cursor:pointer
}
.below {
    background:red;
}
.toggleBtn.active{
    background:blue;   
}

    $(document).ready(function () {
        var content = $('.below').hide();
        $('.toggleBtn').on('click', function () {
            $(this).next('.below').slideToggle();

            $(this).toggleClass('active');
            return false;
        });
        //register the handler to button element inside .below
        $('.below .close').on('click', function () {
            //find the ancestor .below element of the clicked button
            $(this).closest('.below').slideToggle();
        });
    });

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

       var $this = $(this);
       $this.next('.below').slideToggle().siblings('.below').slideUp();
       $this.toggleClass('active').siblings('.toggleBtn.active').removeClass('active');

而不是

     $(this).next('.below').slideToggle();

<强> Fiddle

答案 1 :(得分:1)

使用此:

var the_others = $('.active').not(this);
the_others.removeClass('active');
the_others.next('.below').slideUp();

Fiddle