.head {
height: 100px;
width: 100%;
background-color: pink;
position: fixed;
z-index: 100;
left: 0;
top: 0;
}
.headone {
height: 70px;
background-color: blue;
}
.body {
height: 1000px;
width: 90%;
background-color: lightblue;
margin: 0 auto;
}
.totop {
width: 50px;
height: 50px;
background-color: #fff;
border: 1px solid gray;
position: fixed;
right: 30px;
bottom: 200px;
line-height: 50px;
display: none;
}
<div class="head" id="head">
</div>
<div class="body" id="body">
</div>
<div class="totop" id="totop">
回顶部
</div>
<script>
var head = document.getElementById('head');
var totop = document.getElementById('totop');
window.onscroll = function () {
var scroll = document.documentElement.scrollTop;
if(scroll > 10){
head.className = 'head headone';
totop.style.display = 'block';
}
else {
head.className = 'head';
totop.style.display = 'none';
}
}
totop.onclick = function () {
var timeid = null;
if(timeid){
clearInterval(timeid);
timeid = null;
}
timeid = setInterval( function (){
var current = document.documentElement.scrollTop;
var step = 15;
var target = 0;
if(current>target){
step = -Math.abs(step);
}
if(Math.abs(current - target) <= Math.abs(step)){
clearInterval(timeid);
document.documentElement.scrollTop = target;
rerurn;
}
current += step;
document.documentElement.scrollTop = current;
}, 5);
}
</script>