一键返回顶部(含动画)
一键返回顶部
HTML
svg为一张向上箭头的图片,直接复制即可用
CSS
#top {
width: 50px;
height: 50px;
padding: 4px 0 0 12px;
box-sizing: border-box;
user-select: none;
background-color: #fff;
border-radius: 10px;
box-shadow: 0px 0px 10px #aaa;
position: fixed;
right: 20px;
bottom: 100px;
transition: all 0.3s;
}
#top .top-svg {
fill: none;
stroke: #888;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
position: relative;
left: -4px;
top: 2px;
}
#top:hover {
box-shadow: 0px 0px 10px #777;
}
#top:hover .top-svg {
stroke: #666;
}
JS
var timer = null;
// 绑定页面top盒子的点击事件
document.getElementById('top').onclick = function () {
// 取消浏览器关键帧动画
cancelAnimationFrame(timer);
// 浏览器重绘前调用的动画
timer = requestAnimationFrame(function fn() {
var oTop = document.body.scrollTop || document.documentElement.scrollTop;
if (oTop > 0) {
document.body.scrollTop = document.documentElement.scrollTop = oTop - 70;
timer = requestAnimationFrame(fn);
} else {
cancelAnimationFrame(timer);
}
});
}