我创建了一个虚拟html,在我的示例中,当我点击向左折叠时,左窗格div崩溃,主容器div自动增长但在右窗格div之间错位。我希望在操作过程中所有div都应该显示在同一个地方。
$(function() {
$("#spnColLeft").on("click", function() {
if ($(".left").is(':visible')) {
$(".left").animate({
width: 'hide'
});
$(".mainbody").width($(".left").width() + $(".mainbody").width());
$(this).html("Expand left");
} else {
$(".mainbody").width($(".mainbody").width() - $(".left").width());
$(".left").animate({
width: 'show'
});
$(this).html("Collapse left");
}
});
$("#spnColRight").on("click", function() {
if ($(".right").is(':visible')) {
$(".right").animate({
width: 'hide'
});
$(".mainbody").width($(".right").width() + $(".mainbody").width());
$(this).html("Expand right");
} else {
$(".mainbody").width($(".mainbody").width() - $(".right").width());
$(".right").animate({
width: 'show'
});
$(this).html("Collapse Right");
}
});
});
body {
margin: 0;
}
[id^=maincontent] {
margin: 20px 0;
width: 100%;
overflow: hidden;
}
div > div {
height: 100px;
/*demo*/
float: left;
}
.mainbody {
width: 79%;
background-color: cyan;
}
.left,
.right {
background-color: yellow;
width: 10%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<button id="spnColLeft">colapse Left</button>
<button id="spnColRight">colapse Right</button>
</div>
<div id="maincontent1">
<div class="left"></div>
<div class="mainbody"></div>
<div class="right"></div>
</div>
答案 0 :(得分:0)
有很多方法可以做到这一点,但这个方法很合适。请快速浏览
$(function() {
$("#spnColLeft").on("click", function() {
if ($(".left").is(':visible')) {
$(".left").animate({
width: 'hide'
});
$(".mainbody").width($(".left").width() + $(".mainbody").width());
$(this).html("Expand left");
} else {
$(".mainbody").width($(".mainbody").width() - $(".left").width());
$(".left").animate({
width: 'show'
});
$(this).html("Collapse left");
}
});
$("#spnColRight").on("click", function() {
if ($(".right").is(':visible')) {
$(".right").animate({
width: 'hide'
});
$(".mainbody").width($(".right").width() + $(".mainbody").width());
$(this).html("Expand right");
} else {
$(".mainbody").width($(".mainbody").width() - $(".right").width());
$(".right").animate({
width: 'show'
});
$(this).html("Collapse Right");
}
});
});
&#13;
.main {
margin: 20px 0;
width: 100%;
overflow: hidden;
}
.left,
.right {
background: yellow;
width: 10%;
height: 100px;
}
.left { float: left; }
.right { float: right; }
.center {
height: 100px;
background-color: cyan;
overflow: hidden;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="spnColLeft">colapse Left</button>
<button id="spnColRight">colapse Right</button>
</div>
<div class="main">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
&#13;