最近开始做mui移动端的项目用到了列表,数据多的时候,回到顶部的快捷的功能是很有必要的,找了资料,最后整理如下:
1.回到顶部元素的html代码,代码可以直接放在mui-content里面:
<!--回到顶部-->
<a id="scrollToTop" class="backTop hide"> <span class="mui-icon mui-icon-arrowup"></span> </a>
2.添加一些样式修饰,好让元素悬浮
.hide { display: none; }
.backTop { background: #DDDDDD; border-radius: 50%; position: fixed; right: 10px; bottom: 15px; width: 38px; height: 38px; z-index: 9999; text-align: center; font-size: 18px; color: #666666; padding-top: 8px; opacity: 0.8; }
3.回到顶部的方法要配合上拉,下滑使用:
//回到顶部
function scrollUp() {
var scrollToTopBox = document.getElementById('scrollToTop'); //返回按钮tap
scrollToTopBox.addEventListener('tap', function(e) {
e.stopPropagation();
mui('#pullrefresh').pullRefresh().scrollTo(0, 0, 100); //滚动到顶部
});
// Android上监听原生滚动,iOS上监听div滚动,上拉超过一屏后显示按钮,否则隐藏,可自行在条件判断中修改
if(mui.os.android) {
window.addEventListener('scroll', function(e) {
if(window.pageYOffset >= window.innerHeight && scrollToTopBox.classList.contains('hide')) {
scrollToTopBox.classList.remove('hide');
} else if(window.pageYOffset < window.innerHeight && !scrollToTopBox.classList.contains('hide')) {
scrollToTopBox.classList.add('hide');
}
});
} else {
document.getElementById('pullrefresh').addEventListener('scroll', function() {
if(mui('#pullrefresh').pullRefresh().y <= window.innerHeight * (-1) && scrollToTopBox.classList.contains('hide')) {
scrollToTopBox.classList.remove('hide');
} else if(mui('#pullrefresh').pullRefresh().y > window.innerHeight * (-1) && !scrollToTopBox.classList.contains('hide')) {
scrollToTopBox.classList.add('hide');
}
});
}
}