一、无动画版本,实际效果太过僵硬,切换太快,页面直接滑到了了底部/顶部
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>
本文介绍了一种使用Zepto.js实现从网页当前位置平滑滚动到顶部或底部的方法。通过设置定时器逐步改变滚动位置,实现了动画效果,提升了用户体验。
1232

被折叠的 条评论
为什么被折叠?



