<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<style>
div {
position: fixed;
right: 0;
bottom: 100px;
width: 100px;
height: 100px;
background-color: green;
text-align: center;
line-height: 100px;
display: none;
border-radius: 5px;
z-index: 999;
}
div a {
display: inline-block;
width: 100%;
height: 100%;
color: #eeeeee;
}
</style>
</head>
<body style="height: 18000px;">
<h1>飞雪连天射白鹿 笑看神侠倚碧鸳</h1>
<div id="btn">
<a href="javascript:void(0);">回到顶部</a>
</div>
<script>
function ScrollTop(btnObj, distance) {
this.btnObj = btnObj;//返回顶部div对象
this.distance = distance;//距离顶部距离
var that = this;//当前对象保留
//ie8浏览器(大于2000就显示导航)
this.ie = function () {
document.documentElement.scrollTop > that.distance ? that.btnObj.style.display = "block" : that.btnObj.style.display = "none";
};
//其它浏览器支持的(大于2000就显示导航)
this.other = function () {
window.pageYOffset > that.distance ? that.btnObj.style.display = "block" : that.btnObj.style.display = "none";
};
}
//返回到顶部并且隐藏导航因为都用到这个方法 所以加入原型
ScrollTop.prototype.returnTop = function () {
document.documentElement.scrollTop = 0;
scroll.btnObj.style.display = "none";
};
//判断window.pageYOffset(ie8不支持)是否大于等于0,如果是进入chrome和火狐,如果不是进入ie流程
ScrollTop.prototype.top = function () {
window.pageYOffset >= 0 ? window.onscroll = this.other : document.documentElement.onscroll = this.ie;
this.btnObj.onclick = this.returnTop;
};
//实例化对象
var scroll = new ScrollTop(document.getElementById("btn"), 4000);
scroll.top();
</script>
</body>
</html>
js返回顶部
最新推荐文章于 2023-05-25 10:14:39 发布