如何为网页添加返回顶部按钮
方法一:傻瓜式方法
1.在body的标签添加定位id
<body id="top">
2.在最底部需要返回顶部的位置添加触发定位的代码
<a href="#top">返回顶部</a>
这种方法非常死板,必须让用户移动到正确的位置才能返回顶部。
方法二:稍微升级版
1.在head中加入样式
<style type="text/css">
#returntop{
background:url(images/top.png) no-repeat; /*这里是图标地址*/
bottom: 20px;
right: 20px;
height: 38px; /* Height of image */
width: 38px; /* Width of image */
position:fixed;
_position:absolute;
line-height:30px;
text-align:center;
top:0px;
left:0px;
display:none;
cursor:pointer;
}
</style>
2.在body中加入定位标签,可加在最前面
<div id="returntop"></div>
3.在body中加入相应的script
<script type="text/javascript">
var getDiv=document.getElementById('returntop');
getDiv.οnclick=function(){
window.scrollTo(0,0);
}
window.οnscrοll=function(){
if(document.documentElement.scrollTop){
getDiv.style.display="block";
}else if(document.body.scrollTop){
getDiv.style.display="block";
}else{
getDiv.style.display="none";
}
}
function getWinSize(){
var winHeight=window.innerHeight,winWidth=window.innerWidth;
if(document.documentElement.clientHeight){
winHeight=document.documentElement.clientHeight;
winWidth=document.documentElement.clientWidth;
}else{
winHeight=document.body.clientHeight;
winWidth=document.body.clientWidth;
}
var height=winHeight-50;
var width=winWidth-100;
getDiv.style.top=height+"px";
getDiv.style.left=width+"px";
}
getWinSize();
window.οnresize=getWinSize;
</script>
这种方法特点是当用户滚动屏幕后,会自动在右下角出现返回顶部的图标,用户随时可以返回。相对于第一种方法已经有了一点改进。但人都是喜欢动态的、炫丽的东西,这种方法返回顶部相当生硬,没有渐进式地返回,因此仍需要改进。