展开并折叠div

sj2*_*012 0 html javascript css jquery

扩展和折叠功能目前工作正常,但我想修改功能,所以当我点击Expand 1,然后点击Expand 2,它Expand 1应该自动崩溃.这意味着只div允许一个扩展,而其他所有其他应保持折叠状态.

HTML:

<div class="container">
<div class="header"><span>Expand 1</span>

</div>
<div class="content">
    <ul>
        <li>This is just some random content.</li>
        <li>This is just some random content.</li>
        <li>This is just some random content.</li>
        <li>This is just some random content.</li>
    </ul>
</div>

 <div class="header"><span>Expand 2</span>

</div>
<div class="content">
    <ul>
        <li>This is just some random content.</li>
        <li>This is just some random content.</li>
        <li>This is just some random content.</li>
        <li>This is just some random content.</li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.container {
width:100%;
border:1px solid #d3d3d3;
 }
.container div {
 width:100%;
 }
.container .header {
 background-color:#d3d3d3;
 padding: 2px;
 cursor: pointer;
 font-weight: bold;
 }
 .container .content {
 display: none;
 padding : 5px;
  }
Run Code Online (Sandbox Code Playgroud)

jQuery的

$(".header").click(function () {

$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
    //execute this after slideToggle is done
    //change text of header based on visibility of content div
    $header.text(function () {
        //change text based on condition
        return $content.is(":visible") ? "Collapse" : "Expand";
    });
});

});
Run Code Online (Sandbox Code Playgroud)

例..

http://jsfiddle.net/eK8X5/8290/

Ano*_*shi 5

你可以做,

$(".header").click(function () {
    $header = $(this);
    $content = $header.next();
    $(".content").not($content).slideUp().prev().text("Expand");
    $content.slideToggle(500, function () {
        $header.text(function () {
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});
Run Code Online (Sandbox Code Playgroud)

小提琴

  • 全部折叠,除了使用代码的当前版本$(".content").not($content).slideUp().prev().text("Expand");