javascript - 展开和折叠 div

标签 javascript jquery html css

展开和折叠功能目前工作正常,但我想修改该功能,因此当我单击 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>

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;
  }

查询

$(".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";
    });
});

});

例子..

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

最佳答案

你可以做到,

$(".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";
        });
    });

});

Fiddle

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

关于javascript - 展开和折叠 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33951123/

相关文章:

javascript - 为 ES 模块做 require.resolve

javascript - "$.FunctionName()"和 "FunctionName()"有什么区别?

jquery - 如何在一次 ajax 调用中将多个数组传递给 Controller ​​方法 ASP.net MVC 4

html - 如何在 IE7 模式下保持这两个按钮之间的空间?

javascript - 如何获得字母宽度?

visible=false 的 ASP.NET 控件不能在 javascript 中使用?

jquery - 我可以使用 jQuery 对元素进行计数吗?

javascript - Google Places Autocomplete 不适用于动态生成的输入元素

C# 通过Url计算HTML文档大小

javascript 音频对象与 HTML5 音频标签