需求:当页面滚动到秒杀模块,导航栏自动滑入,否则滑出
JavaScript
获取HTML距离浏览器的距离: document.documentElement,scrollTop
获取元素距离父节点的距离: 元素.offsetTop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.content {
overflow: hidden;
width: 1000px;
height: 3000px;
background-color: pink;
margin: 0 auto;
}
.backtop {
display: none;
width: 50px;
left: 50%;
margin: 0 0 0 505px;
position: fixed;
bottom: 60px;
z-index: 100;
}
.backtop a {
height: 50px;
width: 50px;
background: url(./images/bg2.png) 0 -600px no-repeat;
opacity: 0.35;
overflow: hidden;
display: block;
text-indent: -999em;
cursor: pointer;
}
.header {
position: fixed;
top: -80px;
left: 0;
width: 100%;
height: 80px;
background-color: purple;
text-align: center;
color: #fff;
line-height: 80px;
font-size: 30px;
transition: all .3s;
}
.sk {
width: 300px;
height: 300px;
background-color: skyblue;
margin-top: 600px;
}
</style>
</head>
<body>
<div class="header">我是顶部导航栏</div>
<div class="content">
<div class="sk">秒杀模块</div>
</div>
<div class="backtop">
<img src="./images/close2.png" alt="">
<a href="javascript:;"></a>
</div>
<script>
// 获取 header
let header = document.querySelector('.header');
// 获取sk
let sk = document.querySelector('.sk');
// 当窗口滚动距离 大于或者等于 sk距离父亲的距离 的时候 让header显示
window.addEventListener('scroll', function () {
// 网页距离 : document.documentElement
// scrollTop : 是元素内容滚动的距离
// offsetTop : 是距离自己定位离父元素的距离
if (document.documentElement.scrollTop >= sk.offsetTop) {
//让顶部元素显示
header.style.top = 0;
} else {
// 让顶部元素隐藏
header.style.top = '-80px';
}
});
</script>
</body>
</html>