代码在下面,点击黄色按钮,红色的框总是少一块,最外层div比刚开始的小,是为什么呢
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
.wrap {
width: 100%;
height: 100%;
}
.informationBar {
width: 100%;
height: 10%;
}
.OpenorClose {
width: 100%;
height: 100%;
background: yellow;
}
.menu {
width: 75px;
height: 90%;
float: left;
background: #181f24;
}
.content {
height: 90%;
background: red;
float: left;
}
</style>
</head>
<body>
<div class="wrap">
<div class="informationBar">
<div class="OpenorClose">
点击我
</div>
</div>
<div class="menu"></div>
<div class="content"></div>
<div class="clear"></div>
</div>
</body>
</html>
<script type="text/javascript">
$(".content").css("width", $(window).width() - $(".menu").width() + "px");
var c = true;
$(".OpenorClose").click(function() {
if(c == true) {
$(".menu").css("width", "183px");
$(".content").css("width", $(window).width() - $(".menu").width() + "px");
c = false;
} else {
$(".menu").css("width", "75px");
$(".content").css("width", $(window).width() - $(".menu").width() + "px");
c = true;
}
})
</script>
if(c == true) {
console.log('-----------------c is true-----------');
console.log(`window-- ${ $(window).width() } px`);
$(".menu").css("width", "183px");
// jquery 使用css的时候 会进行页面重绘,你把 .menu 设置为 183 的时候 页面相当于 content 已经被挤到下一行了,这个时候会出现滚动条
// 所以 window 的宽度会出现变化,会把 滚动条的宽度去掉
console.log(`menu -183px-- ${ $(".menu").width() } px`);
console.log(`window-- ${ $(window).width() } px`);
console.log(`true == c ${ $(window).width() - $(".menu").width() } `);
//可以把下面一行注释掉 看页面效果 就知道了
$(".content").css("width", $(window).width() - $(".menu").width() + "px");
/ * 修改方案
var menuW = 183;
$(".content").css("width", $(window).width() - menuW + "px");
$(".menu").css("width", menuW + "px");
*/
c = false;
}
menu的width: 183
content的width: 1658
184+1658 = 1842
你informationBarwidth: 100% 意思是等于wrap的width:100% 意思是等于html的宽度百分百 意思就是浏览器宽度
如果你窗口最大化,你可以看看你电脑的分辨率,大部分是1920*1080 意思是你的浏览器最大化宽度大概是1920左右
所以1920 > 1842 所以有空余的地方
在你的样式 html,body 样式里加一行 overflow:hidden; 的样式。在你计算时窗口的宽会有一个滚动条的宽度。加了后就不会出现这种情况
$(window).width() 替换为 js原生方法 window.innerWidth
补个图片