js返回顶部和滑到页面底部的动画解决方案

本文介绍了一种使用Zepto.js实现从网页当前位置平滑滚动到顶部或底部的方法。通过设置定时器逐步改变滚动位置,实现了动画效果,提升了用户体验。

一、无动画版本,实际效果太过僵硬,切换太快,页面直接滑到了了底部/顶部

var scrollHeight = $(document).height();//文档高度
window.scrollTo(0,scrollHeight);//到达文档底部
window.scrollTo(0,0);//到达文档顶部

二、项目前端架构使用zepto进行的开发,zepto的animate方法只能操作css3的动画属性,无法支持scrollTop方法,故使用了setInterval的方法实现了该效果

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>scrolldemo</title>
		<script src="lib/zepto.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			.btn {
				height: 200px;
				width: 300px;
				font-size: 36px;
				color: deepskyblue;
			}
		</style>
	</head>

	<body>
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<div class="btn btnTop">
			点击回顶部
		</div>
		<div class="btn btnBottom">
			点击到底部
		</div>
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
		<img src="img/wx.jpg" />
	</body>
	<script type="text/javascript">
		$(function() {
			//视窗高度
			var winHeight = $(window).height();
			//文档高度
			var docuHeight = $(document).height();

			//到页面底部
			$('.btnBottom').click(function() {

				//获取当前scrollTop的位置
				var currentScroll = $(window).scrollTop();

				//滑动的步长
				var step = 10;

				//未到达最底部时滚动
				if(currentScroll + winHeight <= docuHeight) {
					setInterval(scrollTimer, 10);
				}

				//步长滚动
				function scrollTimer() {

					if(currentScroll + winHeight < docuHeight) {

						currentScroll = currentScroll + step;
						window.scrollTo(0, currentScroll);
						console.log(currentScroll, docuHeight);

						//当滑动到最底部时清除循环计时器
						if(currentScroll + winHeight >= docuHeight) {

							window.scrollTo(0, docuHeight);
							clearInterval(scrollTimer);
							console.log("结束")

						}
					}

				}
			});
			//滑动到页面顶部
			$('.btnTop').click(function() {

				//获取当前scrollTop的位置
				var currentScroll = $(window).scrollTop();

				//步长
				var step = 10;
				//未到达最顶部时滚动
				if(currentScroll >= 0) {
					setInterval(scrollTimer, 10);
				}

				//步长滑动
				function scrollTimer() {

					if(currentScroll > 0) {

						currentScroll = currentScroll - step;
						window.scrollTo(0, currentScroll);

						console.log(currentScroll);
						if(currentScroll <= 0) {

							window.scrollTo(0, 0);
							clearInterval(scrollTimer);
							console.log("结束")

						}
					}

				}
			})
		})
	</script>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值