如何为网页添加返回顶部按钮

如何为网页添加返回顶部按钮

 

方法一:傻瓜式方法

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>

        这种方法特点是当用户滚动屏幕后,会自动在右下角出现返回顶部的图标,用户随时可以返回。相对于第一种方法已经有了一点改进。但人都是喜欢动态的、炫丽的东西,这种方法返回顶部相当生硬,没有渐进式地返回,因此仍需要改进。

 

 

 

 

 

 

 

 

 

 


 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值