需求:一个定位position:fixed;的菜单栏,移动到底部时依然存在,影响页面美观,我们希望当滚轮移到页面末尾时菜单栏更换为绝对定位。
解决:JS没有直接获取元素距离页面底部距离的函数,因此可利用全文高度-当前高度取得差值来间接判断。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onscroll = function() {
var t2 = document.body.scrollHeight;
var t1 = document.documentElement.scrollTop || document.body.scrollTop;
var t = t2 - t1;
console.log(t);
var oBox = document.getElementById("box");
if (t <= 700) {
oBox.className = 'box-b';
} else {
oBox.className = 'box-t';
}
};
</script>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 1500px;
}
.box-t {
height: 100px;
width: 100px;
background: #CCC;
position: fixed;
/* position: relative; */
left: 81%;
top: 83%;
}
.box-b {
height: 100px;
width: 100px;
background: #6CF;
position: relative;
right: -81%;
bottom: -78%;
}
</style>
</head>
<body>
<div id="box" class="box-b"></div>
</body>
</html>
效果:
滚动条到达一定高度后更换class,实现不再绝对定位。