js实现固定导航操作
思路:当滚动条滚动到某一位置时,动态更改固定定位的top值
固定导航的html结构
<div class="navbar"></div>
<!-- 导航栏 -->
<nav id="nav">
<ul>
<li><a href="#">001</a></li>
<li><a href="#">002</a></li>
<li><a href="#">003</a></li>
<li><a href="#">004</a></li>
<li><a href="#">005</a></li>
</ul>
</nav>
<!-- 内容区 -->
<div class="content"></div>
<button id="btn">返回顶部</button>
固定导航的css样式
<style>
* {
margin: 0;
padding: 0;
}
.navbar {
width: 100%;
height: 300px;
background-color: rgb(238, 134, 134);
}
nav {
width: 100%;
height: 60px;
background-color: aquamarine;
}
ul > li {
list-style: none;
display: inline-block;
margin-right: 30px;
}
ul {
padding-left: 200px;
}
a {
text-decoration: none;
color: black;
width: 60px;
height: 60px;
line-height: 60px;
text-align: center;
}
#btn {
position: fixed;
bottom: 70px;
right: 30px;
/* display: none; */
}
</style>
固定导航的js部分
<script>
//获取导航栏上变的navbar、导航栏nav、内容区content、返回按钮btn
var navbar = document.querySelector(".navbar");
var nav = document.querySelector("#nav");
var content = document.querySelector(".content");
var btn = document.querySelector('#btn');
btn.style.display = 'none'
var Y = 0;
for (var i = 0; i < 100; i++) {
var h3 = document.createElement("h3");
h3.innerHTML = "易烊千玺yyds" + i;
content.appendChild(h3);
}
//控制动画执行的开关
var flag = true;
//监听滚动条
window.onscroll = function (e) {
var ev = e || window.event;
Y = scrollY;
console.log(Y);
if(Y > 500){
btn.style.display = 'block';
}else{
btn.style.display = 'none';
}
//获取滚动条的位置
var page =
document.documentElement.scrollTop || document.body.scrollTop;
console.log(page);
var isHeight = parseInt(
getComputedStyle(navbar, null).height || navbar.currentStyle.height
);
var isNavHeight = parseInt(getComputedStyle(nav, null).height);
console.log(isNavHeight);
console.log(isHeight);
if (page > isHeight) {
nav.style.position = "fixed";
//当滚动条高度大于navbar的高度时,动画出现导航栏
if (flag) {
nav.style.top = -60 + "px";
var top = -60;
console.log(top);
var timer = setInterval(function () {
top += 1;
console.log(top);
nav.style.top = top + "px";
if (top == 0) {
clearInterval(timer);
}
}, 16.7);
}
flag = false;
} else {
nav.style.position = '';
nav.style.top = '';
flag = true;
}
btn.onclick = function(){
var move = scrollY;
var timer_ = setInterval(function(){
move -= 10;
if(move <= 0){
move = 0;
scrollTo(0,move);
clearInterval(timer_)
}
scrollTo(0,move)
},0.1)
}
};
</script>
结果图
结果图