回到顶部案例

html:
<div class='btn-top' id='box'></div>
 
css:
<style>
.btn-top {
width: 50px;
height: 50px;
background: url("./components/top/icon_top.png") no-repeat;
background-size: contain;
cursor: pointer;
position: fixed;
right: 10px;
bottom: 20px;
display: none;
}

</style>
 
js:
<script>
var box = document.getElementById('box')
// 定时器
var timer = null;

// 兼容ie9
window.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (callback) {
// 为了使setTimteout的尽可能的接近每秒60帧的效果
window.setTimeout(callback, 1000 / 60);
}

window.cancelAnimationFrame = window.cancelAnimationFrame ||
Window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.msCancelAnimationFrame ||
window.oCancelAnimationFrame ||
function (id) {
window.clearTimeout(id);
}


window.onscroll = function () {
var oTop = document.documentElement.scrollTop || document.body.scrollTop;
if (oTop > 300) {
box.style.display = 'block';
} else {
box.style.display = 'none';
}
}


box.onclick = function () {
cancelAnimationFrame(timer);
timer = requestAnimationFrame(function fn() {
var oTop = document.documentElement.scrollTop || document.body.scrollTop;
if (oTop > 0) {
document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
timer = requestAnimationFrame(fn);
} else {
cancelAnimationFrame(timer);
}
});
}
</script>
 

 
 
 
 
 
 
 
 
 
 
 

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

posted @ 2017-11-14 09:14  minimissile  阅读(219)  评论(0编辑  收藏  举报