javascript返回顶部插件+源码

时间:2021-10-14 01:35:36

javascript插件->returnTop.js:

		/*
         ** 插件名称returnTop.js
** 调用返回头部单例参数说明
** 调用方式:turn.init(ele,speed);
** oDiv :就是获取返回图标元素
** speed :返回顶部时间的快慢,值越大返回的越快
*/
var turnTop = {}; turnTop.init=function(ele,speed){
turnTop.eve(ele);
turnTop.speed = speed;
}; turnTop.eve = function(ele){
window.onscroll = function(){
if(turnTop.docEleTop ()>0){
ele.style.display = "block";
}else{
ele.style.display = "none";
}
}; ele.onclick = function(){
turnTop.docEleTop ();
var timer = setInterval(function(){
if(parseInt(turnTop.docEleTop ()) > 0){
document.documentElement.scrollTop = document.body.scrollTop = parseInt(turnTop.docEleTop ())-turn.speed;
}else{
clearInterval(timer);
}
},100)
};
};
turnTop.docEleTop = function(){
return document.documentElement.scrollTop || document.body.scrollTop;
};

  

  html页面调用:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#turnTop{
background: url(http://www.zcool.com.cn/images/goTopZcool.png);
width: 34px;height: 100px;display:none;position:fixed;bottom:20px;right:40px;
}
</style>
</head>
<body style="padding-top:3000px;">
<div id="turnTop"></div>
<script src="returnTop.js"></script>
<script>
var oDiv = document.getElementById("turnTop");
turnTop.init(oDiv,100);
</script>
</body>
</html>