<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
button{
width: 80px;
height: 30px;
background-color: red;
color: white;
text-align: center;
border: 0;
border-radius: 3px;
position: fixed;
bottom:20px ;
right: 30px;
z-index: 99;
display: none;
}
</style>
</head>
<body>
<button id="mybtn" name="mybtn" onclick="topFn()">回到顶部</button>
<div style="background-color: black;color: white;padding: 30px;">向下滑动</div>
<div style="background-color: lightgrey;padding: 30px 30px 2500px;">该实例演示如何实现网页返回顶部</div>
<script language="javascript">
var extend=function(target,source){
for(var property in source){
target[property]=source[property];
}
return target;
}
var throttle=function(){
var isClear=arguments[0],fn;
if(typeof isClear==='boolean'){
fn=arguments[1];
fn.__throttleID&&clearTimeout(fn.__throttleID);
}else{
fn=isClear;
param=arguments[1];
var p=extend({
context:null,
args:[],
time:300
},param);
arguments.callee(true,fn);
fn.__throttleID=setTimeout(function(){
fn.apply(p.context,p.args)
},p.time)
}
};
function scrollFn(){
if(document.body.scrollTop>100||document.documentElement.scrollTop>100){
document.getElementById('mybtn').style.display="block";
}else{
document.getElementById('mybtn').style.display="none";
}
}
function topFn(){
document.body.scrollTop=0;
document.documentElement.scrollTop=0;
}
window.onscroll=function(){
throttle(scrollFn,[50]);
};
</script>
</body>
</html>
|