回顶部特效

1.类似淘宝等网站的回顶部特效,用jquery实现,当页面内容滚动距离页面顶部300的时候,出现回顶部按钮,点击后平滑地回到顶部,代码如下:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.top{
width: 50px;
height: 50px;
display: block;
background: #888;
color: #fff;
text-align: center;
line-height: 50px;
font-size: 30px;
text-decoration: none;
position: fixed;
right: 50px;
bottom:50px;
display: none;
}
.top:hover{background: #093}
</style>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(function(){
$(window).scroll(function(){
var t=$(this).scrollTop();
if(t>300){
$(".top").stop().fadeIn(300);
}else{
$(".top").stop().fadeOut(300);
}
});
$(".top").click(function(){
$("body,html").stop().animate({scrollTop:0},300); //html是为了兼容火狐和IE
});
});
</script>
</head>
<body>
<a href="javascript:;" class="top">︿</a>
<!-- 页面内容 -->
<script>
for(var i=0;i<100;i++){
document.write("<h1>"+i+"</h1>");
}
</script>
</body>
</html>

2.用原生js实现回顶部特效的话,代码如下:

<!doctype html >
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<title>Javascript 返回顶部</title>

	<style type="text/css">
		#btn {width:40px; height:40px; position:fixed; right:65px; bottom:10px;display: none; background:url(images/top_bg.png) no-repeat left top;}
		#btn:hover {background:url(images/top_bg.png) no-repeat 0 -39px;}
		.bg {width:1190px; margin:0 auto;}
	</style>
	<script src="script.js"></script>
</head>
<body>

	<div class="bg">
		<img src="images/tb_bg.jpg" alt="" />
	</div>
	<a href="javascript:;" id="btn" title="回到顶部"></a>
</body>
</html>


script.js

//页面加载完毕后触发
window.οnlοad=function(){
	var obtn=document.getElementById('btn');
	var clientHeight=document.documentElement.clientHeight;//用来获取页面可视区的高度,便于回顶部按钮显示隐藏功能实现
	var timer=null;

	var isTop=true;//为了解决回滚时,中途控制了滚动条,迫使回滚停止
	//滚动条滚动时触发
	window.οnscrοll=function(){
		//在滚动的时候判断是否已经到了第二屏
		var osTop=document.documentElement.scrollTop||document.body.scrollTop;//分别兼容ie和chrome等其他浏览器
		if(osTop>=clientHeight){
			obtn.style.display='block';
		}else{
			obtn.style.display='none';
		}
		if(!isTop){
			clearInterval(timer);
		}
		isTop=false;
	}
	obtn.οnclick=function(){
		//设置定时器
		timer=setInterval(function(){
			//首先获取滚动条到顶部的距离
			var osTop=document.documentElement.scrollTop||document.body.scrollTop;//分别兼容ie和chrome等其他浏览器
			var ispeed=Math.floor(-osTop/6);//回顶部一般是先快后慢,之所以加-号,是因为osTop-ispeed回滚的时候不会是0,所以还是会出现clearInterval失效
			document.documentElement.scrollTop=document.body.scrollTop=osTop+ispeed;//因为上面为﹣号,所以这里为加号
			isTop=true;
			console.log(osTop-ispeed);
			//如果不清楚定时器,则当回到顶部的时候拖动滚动条还继续回顶部
			if(osTop==0){
				clearInterval(timer);
			}
		},30);
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值