我正在寻找创建一个在单击完全独立的非父div元素时展开和折叠的div。
以下是我喜欢并且一直在搞乱的扩展/折叠效果的示例。我不确定如何最好地修改下面的代码,以便我可以,例如,点击位于侧边栏中的div,并导致位于标题下方的另一个div说,展开/折叠,将其下方的所有内容向下推。
有问题的展开/折叠div的内容可能是搜索栏,例如,用户可以通过点击侧边栏按钮来显示/隐藏。
$(".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";
});
});
});
.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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="header"><span>Expand</span>
</div>
<div class="content">
<ul>
<li>I'm putting a search bar here.</li>
</ul>
</div>
</div>
答案 0 :(得分:5)
$(".header").click(function() {
$('.content').slideToggle().toggleClass('active');
if ($('.content').hasClass('active')) {
$('.header span').text('Collapse');
} else {
$('.header span').text('Expand');
}
});
$('button').click(function(){
$(".header").trigger('click');
})
.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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="header"><span>Expand</span>
</div>
<div class="content">
<ul>
<li>I'm putting a search bar here.</li>
</ul>
</div>
</div>
<button>another click</button>
答案 1 :(得分:0)
$(".toggle").click(function () {
//getting the content
$content = $(".content")
//open up the content - 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";
});
});
});
.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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="header"><span>Expand</span>
</div>
<div class="content">
<ul>
<li>I'm putting a search bar here.</li>
</ul>
</div>
<div class="toggle">click me</dov>
</div>