<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>Javascript 返回顶部</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.bg {
width: 1190px;
margin: 0 auto;
}
.top {
position: fixed;
right: 50px;
top: 80%;
}
.top{display: none;}
a {
width: 40px;
height: 40px;
overflow: hidden;
background-image: url(images/top_bg.png);
display: block;
}
a:hover {
background-position-y: -40px;
}
</style>
</head>
<body>
<div>
<a id="btn" title="回到顶部"></a>
</div>
<div>
<img src="images/tb_bg.jpg" />
</div>
</body>
<script src="new_file.js"></script>
</html>
(function() {
var Mback = function() {
var self = this;
this.el = document.querySelector(".top");
this.upclick = document.getElementById("btn");
window.onscroll = function() {
var scroT = document.documentElement.scrollTop || document.body.scrollTop;
if(scroT >= 850) {
self.el.style.display = 'block';
} else {
self.el.style.display = 'none';
}
}
this.upclick.addEventListener('click', function() {
console.log("回到顶部");
self.backtop();
});
this.timer = null;
};
Mback.prototype.backtop = function() {
clearInterval(this.timer);
this.timer = setInterval(function() {
this.h = document.documentElement.scrollTop || document.body.scrollTop;
this.speed = Math.ceil(this.h / 5);
if(document.documentElement.scrollTop || document.body.scrollTop> 0) {
console.log(this.h - this.speed);
document.documentElement.scrollTop = document.body.scrollTop = Math.floor(this.h - this.speed);
} else {
clearInterval(this.timer);
}
}, 50);
}
var mback = new Mback();
})();