摘要
5年的代码生涯,逐渐琢磨出一个道理——困难都是想象出来的,真去做了也没那么难。就像写代码,遇到复杂的就百度,复制粘贴感觉不错,可自己还是那个自己,问题还是那个问题,遇到了,心里还是有一丝恐惧、一丝好奇。
侧滑效果,最早见到还是在qq中,现在一步步实现下,就算征服吧!
效果
体验
思路
1、首先将两层view叠放,由于小程序页面的最外层支持上下滑动,为了防止干扰,底层view与顶层view都采用position: fixed
布局,即不随页面滑动而滑动的布局
2、外层view设置触摸事件的监听,由于有频繁用户交互的效果在小程序上表现是比较卡顿的,可使用 WXS 函数用来响应小程序事件
3、监听到触摸事件后通过this.selectComponent(‘xxx’).setStyle(‘动画’)来控制顶层view的滑动
代码
wxml
<wxs module="test" src="./sidebar.wxs"></wxs>
<view class="page">
<view class="page-bottom">
<view class="page-content">
<view class="wc">
<text>底层容器</text>
</view>
</view>
</view>
<view data-width="{{windowWidth}}" bindtouchmove="{{test.touchmove}}" bindtouchend="{{test.touchend}}" bindtouchstart="{{test.touchstart}}" class="page-top" style="color:white;">
<view class="page-content">
<view class="wc">
<text>顶层容器</text>
</view>
</view>
</view>
</view>
wxss
.page-bottom{
height: 100%;
width: 750rpx;
position: fixed;
background-color: yellowgreen;
z-index: 0;
}
.wc{
color: white;
padding: 30rpx 0 30rpx 40rpx;
}
.page-content{
padding-top: 300rpx;
}
.page-top{
height: 100%;
position: fixed;
width: 750rpx;
background-color: tomato;
z-index: 0;
transition: All 0.4s ease;
-webkit-transition: All 0.4s ease;
}
wxs
var newmark = startmark = 0
var status = 0
var moveDistance = 0.75
function touchstart(e, ins) {
var pageX = (e.touches[0] || e.changedTouches[0]).pageX
startmark = newmark = pageX
}
function touchmove(e, ins) {
var pageX = (e.touches[0] || e.changedTouches[0]).pageX
newmark = pageX
var data = {
windowWidth: e.target.dataset.width
}
if (startmark < pageX) {
if (data.windowWidth * moveDistance > Math.abs(newmark - startmark)) {
ins.selectComponent('.page-top').setStyle({
transform: 'translateX(' + Math.min(data.windowWidth * moveDistance, ((status == 1 ? data.windowWidth * moveDistance : 0) + newmark - startmark)) + 'px)'
})
}
}
if (startmark > pageX) {
ins.selectComponent('.page-top').setStyle({
transform: 'translateX(' + Math.max(0, ((status == 1 ? data.windowWidth * moveDistance : 0) + newmark - startmark)) + 'px)'
})
}
}
function touchend(e, ins) {
var pageX = (e.touches[0] || e.changedTouches[0]).pageX
newmark = pageX
var data = {
windowWidth: e.target.dataset.width
}
if (startmark < pageX) {
if (data.windowWidth * 0.2 < Math.abs(newmark - startmark)) {
ins.selectComponent('.page-top').setStyle({
transform: 'translateX(' + (data.windowWidth * moveDistance) + 'px)'
})
status = 1 // 展开状态
} else {
ins.selectComponent('.page-top').setStyle({
transform: 'translateX(0px)'
})
status = 0 // 收起状态
}
}
if (startmark > newmark) {
ins.selectComponent('.page-top').setStyle({
transform: 'translateX(0px)'
})
status = 0 // 收起状态
}
}
module.exports = {
touchstart: touchstart,
touchmove: touchmove,
touchend: touchend
}
结语
这个思路用到了很多小程序方面的知识,读者可细细的去体验一下,相信收获颇多,知识是散的,慢慢进步,学会这个简单的,相信更复杂的交互也是有思路的