几乎每个网页底部都会有返回顶部按钮,而根据效果不同,实现的方式也有很多种,这里参考其他网友的实现方法做了下优化,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>返回顶部</title>
<style>
*{margin:0;padding:0}
#main{
width:800px;
height:3000px;
background:#f9f9f9;
margin:0 auto;
position:relative;
}
.go_top{
position:fixed;
display:none;
}
.close{
width:48px;
height:15px;
border:1px solid rgba(0,0,0,0.5);
margin-bottom:5px;
text-align:center;
cursor:pointer;
}
.close p{
font-size:12px;
color:rgba(0,0,0,0.5);
height:15px;
line-height:15px;
}
.top{
width:50px;
height:50px;
background:url(bg2.png) no-repeat 0px -600px;
background:red;<!--没有背景图片,用红色代替-->
opacity:0.3;
cursor:pointer;
}
.top:hover{
opacity:0.5;
}
</style>
</head>
<body>
<div id="main">
<p>文章顶部</p>
<div id="Top" class="go_top">
<div class="close" onclick="closeTop()"><p>关 闭</p></div>
<div id ="goTop" class="top" onclick="gotoTop()" title="返回顶部" alt="Top"></div>
</div>
</div>
<script>
var Top = document.getElementById("Top");
var goTop = document.getElementById("goTop");
var closedTop=true;
//自适应按钮的位置
window.onload = function(){
var main = document.getElementById("main");
var screenw = document.documentElement.clientWidth || document.body.clientWidth;
var screenh = document.documentElement.clientHeight || document.body.clientHeight;
Top.style.left=(screenw - main.offsetWidth)/2 + main.offsetWidth + 10+"px";
Top.style.top=screenh-Top.offsetHeight - 100 + "px";
}
//关闭按钮
function closeTop(){
Top.style.display = "none";
closedTop=false;
}
//根据网页所处位置显示返回顶部按钮
window.onscroll = function(){
if(closedTop){
if(document.documentElement.scrollTop){
if(document.documentElement.scrollTop<300){
Top.style.display = "none";
}else{
Top.style.display = "block";
}
}
if(document.body.scrollTop){
if(document.body.scrollTop<300){
Top.style.display = "none";
}else{
Top.style.display = "block";
}
}
}
}
//点击按钮返回顶部
function gotoTop(){
document.documentElement.scrollTop = document.body.scrollTop = 0;
Top.style.display = "none";
}
</script>
</body>
</html>
参考文章:http://www.cnblogs.com/jingangel/archive/2012/03/08/2385939.html