窗口发生滚动时候,导航栏和头部定位
<!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: 0;
padding: 0;
}
/* body {
height: 3000px;
} */
.nav {
height: 200px;
text-align: center;
line-height: 200px;
}
.header {
height: 100px;
width: 100%;
line-height: 100px;
color: #ffffff;
font-size: 20px;
background-color: orange;
padding-left: 50px;
}
.oDiv {
width: 50px;
text-align: center;
font-size: 14px;
background-color: #eee;
position: absolute;
top: 500px;
right: 100px;
}
.oDiv a {
display: block;
text-decoration: none;
padding: 5px 5px 0 5px;
height: 45px;
text-align: center;
border-bottom: 1px solid red;
}
.oDiv a:nth-last-child(2) {
line-height: 40px;
color: #000;
}
.oDiv a:nth-last-child(1) {
line-height: 40px;
color: #000;
border-bottom: none;
}
.oDiv a:hover {
background-color: orange;
color: #fff;
font-weight: bold;
}
.oDiv .hide {
display: none;
}
.fixed-top {
position: fixed;
top: 0;
}
.fixed-div {
position: fixed;
top: 100px;
}
p {
height: 500px;
width: 100%;
line-height: 200px;
text-align: center;
}
</style>
</head>
<body>
<div class="nav">滚动此页</div>
<div class="header">我是头部</div>
<p>内容一</p>
<p>内容二</p>
<p>内容三</p>
<div class="oDiv">
<a href="#" class="">爱逛<br>好货</a>
<a href="#" class="center-a">好店<br>直播</a>
<a href="#" class="center-a">品质<br>特色</a>
<a href="#" class="center-a">实惠<br>特卖</a>
<a href="#" class="center-a">猜你<br>喜欢</a>
<a href="#" class="center-a hide">∧<br>顶部</a>
<a href="#" class="center-a">反馈</a>
<a href="#" class="">举报</a>
</div>
<script>
let nav = document.querySelector('.nav');
let header = document.querySelector('.header');
let oDiv = document.querySelector('.oDiv');
//获取header到顶部的距离
let origOffsetY = header.offsetTop;
//获取导航栏div到顶部的距离
let origDivOffsetY = oDiv.offsetTop - header.offsetHeight;
//定义导航栏返回顶部显示的高度
let navHeight = oDiv.offsetTop;
//滚动事件
window.onscroll = function() {
// var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// console.log(window.scrollY, scrollTop); //两个值相同
// console.log(window.scrollY, origDivOffsetY);
//头部定位
window.scrollY >= origOffsetY ? header.classList.add('fixed-top') : header.classList.remove('fixed-top');
//导航栏定位
window.scrollY >= origDivOffsetY ? oDiv.classList.add('fixed-div') : oDiv.classList.remove('fixed-div');
//导航栏上返回顶部链接显示
window.scrollY >= navHeight ? oDiv.querySelector('.hide').style.display = 'block' : oDiv.querySelector('.hide').style.display = 'none';
}
</script>
</body>
</html>
效果图: