请问谁有这页面回到顶部的完整代码呢,谢谢了
请问谁有这页面回到顶部的完整代码呢, 有过程解释的最好,谢谢了
请问谁有这页面回到顶部的完整代码呢, 有过程解释的最好,谢谢了
2018-07-20
<!DOCTYPE html>
<html>
<head>
<title>Javascript 回到顶部效果</title>
<style>
#btn {
width:40px;
height:40px;
position:fixed;
left:50%;
display:none;
margin-left:610px;
bottom:30px;
background:url(http://img1.sycdn.imooc.com//535e0dc100010e9c00400080.jpg) no-repeat left top;
}
#btn:hover {
background:url(http://img1.sycdn.imooc.com//535e0dc100010e9c00400080.jpg) no-repeat 0 -39px;
}
.box {
width:1190px;
margin:0 auto;
}
</style>
<script>
window.onload = function () {
//设置所需变量
var oBtn = document.getElementById('btn');
var scrollTop = 0;
var timer = null;
//滚动时按钮的显示与隐藏
window.onscroll = function () {
scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//可视区高度
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
if(scrollTop >= clientHeight) {
oBtn.style.display = 'block';
}
else {
oBtn.style.display = 'none';
}
};
//点击回到顶部
oBtn.onclick = function () {
//设置定时器
timer = setInterval(function () {
// var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//定义缓冲速度
var iSpeed = scrollTop/5;
//顶部关闭定时器
if (scrollTop == 0) {
clearInterval(timer);
}
document.documentElement.scrollTop = document.body.scrollTop = Math.floor(scrollTop - iSpeed);
console.log(scrollTop);
},30);
};
};
</script>
</head>
<body>
<div class="box">
<img src="http://img1.sycdn.imooc.com//535e0ce800015b7511902787.jpg" />
</div>
<a href="javascript:;" id="btn" title="回到顶部"></a>
</body>
</html>
举报