CSS JS 固定位置侧边栏



我有 2 个块 - 一个固定位置,另一个在它旁边。我希望固定块在单击按钮后增加长度,第二个块减小大小并再次单击所有内容以将其恢复到原始状态。固定块将是侧边栏菜单,永久粘合。

一切都应该以 100% 的宽度发生。

怎么做,但重要的是固定块和后者的宽度应该以像素为单位指定,而不是以百分比指定

这是要做的吗?

jQuery(document).ready(function($) {
jQuery(".btn").click(function() {
var div1 = jQuery(".left");
var div2 = jQuery(".right");
if (div1.width() < 200) {
div1.animate({
width: "25%"
}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
div2.animate({
width: "75%"
}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
} else {
div1.animate({
width: "5%"
}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
div2.animate({
width: "95%"
}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
}
});
});
.container {
width: 100%;
margin: 0 auto;
}
.left {
float: left;
position: fixed;
width: 5%;
height: 100%;
background: pink;
z-index: 5;
}
.right {
float: right;
position: relative;
width: 95%;
height: 300px;
background: green;
}
.content {
float: left;
position: relative;
width: 100%;
height: 100px;
background: silver;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="left">
<input type="button" value="click" class="btn">
</div>
<div class="right">
<div class="content"> abc </div>
</div>
</div>

一切都应该以 100% 的宽度进行。

。以像素为单位,而不是以百分比为单位。

你确定不是相反的吗?尝试基于%而不是pxrem制作 yor css 会更好(除非需要在px中执行此操作(

无论如何,我修复了您的代码,但是在%中,如果需要,您可以从现在开始使用px:

jQuery(document).ready(function($) {
jQuery(".btn").click(function() {
var leftDiv = jQuery(".left");
var rightDiv = jQuery(".right");
console.log("leftDiv width: " + leftDiv.width() +
" - " + "rightDiv width: " + rightDiv.width())

var minWidthForRight = $('.container').width() - 300;
var maxWidthForRight = $('.container').width() - 100;
if (leftDiv.width() < 200) {

leftDiv.animate({
width: "300px",

}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
rightDiv.animate({
width: minWidthForRight
}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
} else {
leftDiv.animate({
width: "100px"
}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
rightDiv.animate({
width: maxWidthForRight
}, {
duration: 200,
specialEasing: {
width: "linear"
}
});
}
});
});
.container {
width: 100%;
margin: 0 auto;
}
.left {
float: left;
position: fixed;
width: 150px;
height: 300px;
background: pink;
z-index: 5;
}
.right {
float: right;
position: relative;
width: 95%;
height: 300px;
background: green;
resize: horizontal;
}
.content {
float: left;
position: relative;
width: 100%;
height: 100px;
background: silver;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="left">
<input type="button" value="click" class="btn">
</div>
<div class="right">
<div class="content"> abc </div>
</div>
</div>

编辑

是的,可以将左侧保持在 px 中,左侧以 % 为单位,而不是 % 本身,而是根据屏幕分辨率以 px 计算。

基本上,您采用容器宽度并"消除"您在动画中指定的宽度:

var minWidthForRight = $('.container').width() - 300;

右侧为:300 + (100% - 300 ),左侧相同:100 + (100% - 100 )

最新更新