
先上图说明一下实现的效果,如下面动图:
效果展现图效果实现代码建立在vue项目工程之上,但是具体实现原理通用,读者可根据自身需求进行迁移。
1、构造一个浮动盒子,样式代码如下
.upglidebox { position: fixed; height: 600px; width: 100%; background-color: #fff; border-top-right-radius: 40px; border-top-left-radius: 40px;}
其中定位方式为了与本来的父容器不造成滑动上的冲突,需要设成fixed。
2、使用HTML5触摸事件(touchstart、touchmove和touchend),分别用来记录手指操作对盒子的影响。通过屏蔽系统本身的滑动效果,自己设置实现盒子随手指上下滑的行为。
mounted () {
? ? let distance = 0, startPageY = 0, endPageY = 0, curHeight = 0;
? ? const upglideboxDom = this.$refs['upglidebox']
? ? upglideboxDom.addEventListener('touchstart', e => {
? ? ? startPageY = e.changedTouches[0].pageY
? ? })
? ? upglideboxDom.addEventListener('touchend', e => {
? ? ? // 记录上滑框的当前高度
? ? ? curHeight = distance;
? ? })
? ? const boxHeight = upglideboxDom.clientHeight
? ? const boxTop = parseFloat(upglideboxDom.style.top.replace('px', ''))
? ? const maxScrollheight = boxHeight - (document.documentElement.clientHeight - boxTop)
? ? // let isScrollMax = false
? ? upglideboxDom.addEventListener('touchmove', e => {
? ? ? // 屏蔽盒子默认的滑动行为
? ? ? e.preventDefault()
? ? ? endPageY = e.changedTouches[0].pageY
? ? ? distance = startPageY - endPageY + curHeight
? ? ? // 往下滑就瞬间返回初始位置
? ? ? if (distance < 0) {
? ? ? ? distance = 0
? ? ? }
? ? ? // 最多只能让盒子滑出贴近底部
? ? ? if (distance > maxScrollheight) {
? ? ? ? distance = maxScrollheight
? ? ? }
? ? ? this.upglideboxStyle = `
? ? ? ? top:400px;
? ? ? ? transform: translateY(${-distance}px);
? ? ? `;
? ? }, { passive: false })
? }
由于浏览器必需要在执行事件解决函数之后,才能知道有没有掉用过 preventDefault() ,浏览器不能及时响应滚动,略有推迟。所以为了让页面滚动的效果如丝般顺滑,从 chrome56 开始,在 window、document 和 body 上注册的 touchstart 和 touchmove 事件解决函数,会默认为是 passive: true。浏览器忽略 preventDefault() 即可以第一时间滚动了,其中{ passive: false }就是为了让? e.preventDefault()起效。
由于时间起因暂时记录于此,代码后续上传,后续会优化成相似豆瓣app电影评论页面上滑框相似效果。若有更好的实现办法,烦请指教。