美文网首页
手动实现 Swiper 视窗滑动效果

手动实现 Swiper 视窗滑动效果

作者: 夏海峰 | 来源:发表于2019-08-24 18:08 被阅读0次
swiper

需求说明:在微信小程序中,手动实现 Swiper 组件的Tab切换、滑动效果,当点击的字母大于当前字母时,要求向左滑动;当点击的字母小于当前字母时,要求向右滑动(如上图示)。

代码实现

1、使用微信小程序原生开发,给三个Tab项绑定tap事件(见demo.wxml文件),在事件处理逻辑中,动态地改变当前Tab项的索引,并根据Tab索引变大或变小,来判断给定内容块to-leftto-right的动画类(见demo.js文件)。

2、在demo.wxss文件中,定义了两个 keyframes动画,使用transform属性来改变 X 轴方向上的位移。内容块根据当前Tab索引,来切换display = none | block,每次切换显示与隐藏时,执行to-leftto-right动画效果。相关重点,已标注在demo.wxss文件中。

# demo.wxml

<view class='page'>
    <!-- Tabs -->
    <view class='tabs'>
        <text data-index='1' class="{{idx=='1' ? 'on': ''}}" bindtap="click">A</text>
        <text data-index='2' class="{{idx=='2' ? 'on': ''}}" bindtap="click">B</text>
        <text data-index='3' class="{{idx=='3' ? 'on': ''}}" bindtap="click">C</text>
    </view>

    <!-- 内容块 -->
    <view class='contents'>
        <view class="{{idx=='1' ? 'on '+swiper: ''}}">A</view>
        <view  class="{{idx=='2' ? 'on '+swiper: ''}}">B</view>
        <view class="{{idx=='3' ? 'on '+swiper: ''}}">C</view>
    </view>
</view>
# demo.wxss

.page {
    height: 100%;
    width: 100%;
    background: rgba(245, 245, 245, 0.8);
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

/* Tabs样式 */
.tabs {
    display: flex;
    height: 100rpx;
}
.tabs > text {
    flex: 1;
    display: block;
    text-align: center;
    border-bottom: 4rpx solid transparent;
    margin: 0 5rpx;
    height: 100rpx;
    line-height: 100rpx;
    transform: all ease 1s;
    font-weight: bold;
    font-size: 50rpx;
}
.tabs > text.on {
    border-color: rgba(0, 122, 204, 1);
    color: rgba(0, 122, 204, 1);
}

/* 内容区域样式 */
.contents {
    position: absolute;
    top: 135rpx;
    left: 0;
    right: 0;
    border: 1rpx solid rgba(0, 122, 204, 0.7);
    display: flex;
    height: 300rpx;
    line-height: 300rpx;
}
.contents > view {
    position: absolute;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;
    background: white;
    display: none;
    vertical-align: middle;
    text-align: center;
    font-size: 200rpx;
    color: rgba(0, 122, 204, 1);
    font-weight: bold;
}
.contents > view.on { display: block; }    /*重点*/


.to-right { animation: toRight 1s 1; }
.to-left { animation: toLeft 1s 1; }

/* 动画-向右移动 */
@keyframes toRight {
    from { transform: translateX(-750rpx); }   /*重点*/
    to { transform: translateX(0); }
}
/* 动画-向左移动 */
@keyframes toLeft {
    from { transform: translateX(750rpx); }   /*重点*/
    to { transform: translateX(0); }
}
# demo.js

Page({
  data: {
    swiper: '',  // 动态样式
    idx: 1      // 当前Tab索引
  },
  click: function(e) {
    const idx = e.target.dataset.index
    // 当前Tab索引变大时,向左滑动;当前Tab变小时,向右滑动。
    const swiper = idx > this.data.idx ? 'to-left' : 'to-right';
    this.setData({idx: idx, swiper: swiper})
  },
})
# demo.json

{
  "navigationBarTitleText": "Swiper实现"
}


往期实践笔记:


本篇结束!

相关文章

网友评论

      本文标题:手动实现 Swiper 视窗滑动效果

      本文链接:https://www.haomeiwen.com/subject/pxmqectx.html