方案一:纯CSS实现
当给div.top设置position为fixed的时候,它就会脱离文档流,不再占据原来的位置,会让下面的div.bottom往上移动,,div.top会覆盖div.bottom.为了解决这个问题,我们在div.top添加了一个div.empty,这个元素没有任何实际意义,让他的宽高等于div.top的宽高.占据div.top的原来的位置,避免div.bottom上浮,造成遮盖的现象.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0px;
padding: 0px;
}
.top{
width: 100%;
height: 100px;
z-index: 301;
background-color: red;
position: fixed;
}
.empty{
width: 100%;
height: 100px;
}
</style>
</head>
<body>
<div class="app">
<div class="top"></div>
<div class="empty"></div>
<div class="bottom">
<h1>分别是贷记卡看来大家撒1 </h1>
<h1>分别是贷记卡看来大家撒2 </h1>
<h1>分别是贷记卡看来大家撒3 </h1>
<h1>分别是贷记卡看来大家撒4 </h1>
<h1>分别是贷记卡看来大家撒5 </h1>
<h1>分别是贷记卡看来大家撒6 </h1>
... <!--重复30次-->
</div>
</div>
</body>
</html>
方案二:使用JS来实现
此方法主要利用的JS中DOM的document.documentElement.scollTop这个属性,获取页面下滑的高度,通过事件监听来判断当下滑高度发生变化时,就给div.top元素添加新的类--.topsc,在此类中设置position为fixed;当高度为零时,就去除.topsc这个类.
- 添加类:
document.getElementsByClassName("top")[0].classList.add("topsc")- 删除类: document.getElementsByClassName("top).classList.remove("topsc")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0px;
padding: 0px;
}
.top{
width: 100%;
height: 100px;
background-color: red;
}
.topsc {
width: 100%;
height: 100px;
padding: 0px;
margin: 0px;
z-index: 301;
background-color: red;
position: fixed;
}
</style>
</head>
<body>
<div class="app">
<div class="top"></div>
<div class="bottom">
<h1>分别是贷记卡看来大家撒1 </h1>
<h1>分别是贷记卡看来大家撒2 </h1>
<h1>分别是贷记卡看来大家撒3 </h1>
<h1>分别是贷记卡看来大家撒4 </h1>
<h1>分别是贷记卡看来大家撒5 </h1>
<h1>分别是贷记卡看来大家撒6 </h1>
... <!--重复30次-->
</div>
</div>
</body>
</html>
<script>
window.onscroll = function(){
console.log(document.documentElement.scrollTop)
if(document.documentElement.scrollTop >= 1){
document.getElementsByClassName("top")[0].classList.add("topsc")
}else{
document.getElementsByClassName("top")[0].classList.remove("topsc")
}
</script>
