点击页面图标,返回到页面顶部,mui中提供了一个方法:scrollTo(),滚动到特定位置。
scrollTo( xpos , ypos [, duration] )
三个参数说明:
xpos
Type: Integer
要在窗口文档显示区左上角显示的文档的 x 坐标
ypos
Type: Integer
要在窗口文档显示区左上角显示的文档的 y 坐标
duration
Type: Integer
滚动时间周期,单位是毫秒
滚动到顶部参数设置如下:scrollTo(0,0,500); 也就是说只需要设置第三个参数多少毫秒滚动到顶部。
mui('.mui-scroll-wrapper').scroll().scrollTo(0,0,100);//100毫秒滚动到顶
上面代码是官方提供的,而我们在实际应用中科院直接使用即可:
mui.scrollTo(0,0,100)
下面是完整代码,亲测有效,JS部分:
mui.plusReady(function() {
//回到顶部
var scrollToTopBox = document.getElementById('scrollToTop');
//返回按钮tap
scrollToTopBox.addEventListener('tap', function(e) {
console.log('click here')
e.stopPropagation();
//mui('#pullrefresh').pullRefresh().scrollTo(0, 0, 100); //滚动到顶部
//window.scrollTo(0, 0, 1000);
mui.scrollTo(0,1000);
});
//Android上监听原生滚动,iOS上监听div滚动,上拉超过一屏后显示按钮,否则隐藏,可自行在条件判断中修改
if (mui.os.android) {
console.log('android')
window.addEventListener('scroll', function(e) {
if (window.pageYOffset >= window.innerHeight && scrollToTopBox.classList.contains('hide'))
scrollToTopBox.classList.remove('hide');
else if (window.pageYOffset
scrollToTopBox.classList.add('hide');
});
} else {
console.log('ios')
console.log(window.innerHeight)
document.getElementById('pullrefresh').addEventListener('scroll', function() {
console.log('scrolling...')
if (mui('#pullrefresh').pullRefresh().y <= window.innerHeight(-1) && scrollToTopBox.classList.contains('hide')){
scrollToTopBox.classList.remove('hide');
console.log('remove hide')
}
else if (mui('#pullrefresh').pullRefresh().y > window.innerHeight(-1) && !scrollToTopBox.classList.contains('hide')){
scrollToTopBox.classList.add('hide');
console.log('add hide')
}
});
}
});
HTML部分:
css部分:
.hide { display: none; }
.backTop { background: #DDDDDD; border-radius: 50%; position: fixed; right: 10px; bottom: 10%; width: 38px; height: 38px; z-index: 9999; text-align: center; font-size: 18px; color: #666666; padding-top: 8px; opacity: 0.8; }
.s1,.s2{width:100%;height: 250px;background-color: #eee;}
.s2{background-color: #23A6D5;}
思路整理
返回顶部图标默认是隐藏状态,当滚动一屏后会自动出现,代码中使用window.innerHeight来获取当前设备屏幕高度,然后和网页滚动的高度window.pageYOffset进行比较来决定返回顶部图标是显示还是隐藏。
当点击返回顶部按钮后,触发代码
mui.scrollTo(0,0,100)
滚动返回顶部。