实现思路
HTML部分给导航栏及回到顶部css设置为固定定位fixed,通过js的onscroll滚动事件获取页面滚动距离进行判断,当滚动距离大于10时,显示回到顶部按钮,改变导航栏高度。当点击回到顶部按钮时,调用定时器方法,改变scrollTop的值回到顶部。
HTML
head导入向上箭头链接
<link href="//netdna.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
body里面代码
<!-- 导航栏start -->
<div class="header" id="header-top">
<ul>
<li>吃惊</li>
<li>卧槽</li>
<li>我的天</li>
<li>HTML</li>
<li>JavaScript</li>
</ul>
</div>
<!-- 导航栏end -->
<!-- 回到顶部图标start -->
<!-- 通过导入font-awesome图标库展示向上箭头-->
<div class="icon" id="icon">
<i class="fa fa-chevron-up fa-3x" aria-hidden="true"></i>
</div>
<!-- 回到顶部图标end -->
CSS
*{
margin: 0;
padding: 0;
}
body{
height: 1500px;
}
.header{
width: 100%;
height: 100px;
position: fixed;
top: 0;
left: 0;
background-color: #00FFFF;
transition: height 0.3s;
}
.header.fixed{
height: 50px;
box-shadow: 0 0 1px 0 rgba(0,0,0,.3),
0 0 6px 2px rgba(0,0,0,.15);
}
.header li{
float: left;
margin-left: 50px;
margin-top: 15px;
list-style: none;
}
.icon{
background-color: rgba(0,0,0,0.2);
position:fixed;
bottom: 50px;
right: 30px;
}
Js代码
<script type="text/javascript">
var headerTop=document.getElementById("header-top");
var icon=document.getElementById("icon");
window.onscroll=function(){
var scrolltop=document.documentElement.scrollTop;
console.log(scrolltop);
//console.log(bodytop);
if(scrolltop>10){
headerTop.className='header fixed';
icon.style.display="block";
}
else{
headerTop.className='header';
icon.style.display="none";
}
}
//点击向上按钮,回到顶部实现
var timerId=null;
icon.onclick=function(){
if(timerId){
clearInterval(timerId);
timerId=null;
}
timerId=setInterval(function(){
//设置每次移动的距离
var step=10;
//设置头顶距离
var target=0;
//获取当前位置
var current=document.documentElement.scrollTop;
if(current>target){
step=-Math.abs(step);
}
//判断目标是否到达位置
if(Math.abs(current-target)<=Math.abs(step)){
clearInterval(timerId);
document.documentElement.scrollTop=target;
return;
}
current+=step;
document.documentElement.scrollTop=current;
},5)
}
</script>
实现效果
实现前
实现后