小程序满屏左右滑动swiper幻灯片代码

微信   2025-01-21 15:27   92   0  

要实现小程序中的满屏左右滑动幻灯片效果,你可以使用小程序的swiper组件,或者通过触摸事件来实现自定义的滑动效果。以下是两种方法的简要介绍和代码示例:

方法一:使用swiper组件

swiper组件是微信小程序中用于实现轮播图或幻灯片效果的内置组件。你可以通过设置其属性来实现自动轮播、添加指示点等功能。

示例代码‌:

index.wxml

<view class="container">
  <swiper
    indicator-dots="{{indicator_dots}}"
    indicator-color="{{indicator_color}}"
    indicator-active-color="{{indicator_active_color}}"
    autoplay="{{autoplay}}"
    interval="{{interval}}"
    circular="{{circular}}"
    class="swiper-container"
  >
    <swiper-item wx:for="{{imgUrls}}" wx:key="item">
      <image src="{{item}}" mode="widthFix" class="slide-image"></image>
    </swiper-item>
  </swiper>
</view>


index.wxss

.container {
  width: 100%;
  height: 100%;
}

.swiper-container {
  width: 100%;
  height: 100%;
}

.slide-image {
  width: 100%;
  height: 100%;
}


index.js

Page({
  data: {
    indicator_dots: true,
    indicator_color: "#ffffff",
    indicator_active_color: "#F8626E",
    autoplay: true,
    interval: 3000,
    circular: true,
    imgUrls: [
      '../../images/banner-1.png',
      '../../images/banner-2.png',
      '../../images/banner-3.png'
    ]
  }
});


方法二:通过触摸事件实现左右滑动

如果你需要更复杂的滑动效果,或者想要自定义滑动行为,可以通过监听触摸事件(touchStarttouchMovetouchEnd)来实现。

示例代码‌(简化版):

index.wxml

<view class="container" 
       bindtouchstart="touchStart" 
       bindtouchmove="touchMove" 
       bindtouchend="touchEnd">
  <view class="slide {{currentSlide === 0 ? 'active' : ''}}">Slide 1</view>
  <view class="slide {{currentSlide === 1 ? 'active' : ''}}">Slide 2</view>
  <view class="slide {{currentSlide === 2 ? 'active' : ''}}">Slide 3</view>
</view>

index.js

Page({
  data: {
    currentSlide: 0
  },
  touchStart: function(e) {
    this.startX = e.touches[0].pageX;
  },
  touchMove: function(e) {
    this.endX = e.touches[0].pageX;
  },
  touchEnd: function(e) {
    const diffX = this.endX - this.startX;
    if (diffX > 50) {
      // 右滑
      this.setData({
        currentSlide: Math.max(this.data.currentSlide - 1, 0)
      });
    } else if (diffX < -50) {
      // 左滑
      this.setData({
        currentSlide: Math.min(this.data.currentSlide + 1, 2)
      });
    }
  }
});

index.wxss

.container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.slide {
  width: 100%;
  height: 100%;
  position: absolute;
  transition: transform 0.5s ease;
}

.slide.active {
  transform: translateX(0);
  z-index: 10;
}

/* 初始位置设置,根据需要调整 */
.slide:nth-child(1) { transform: translateX(0); }
.slide:nth-child(2) { transform: translateX(100%); }
.slide:nth-child(3) { transform: translateX(200%); }

注意‌:方法二中的CSS和JS逻辑需要根据实际滑动效果和页面布局进行调整,上述代码仅为示例。

选择合适的方法

  • 如果你只需要简单的轮播图效果,建议使用swiper组件,因为它更简洁且易于实现。

  • 如果你需要自定义滑动行为或实现更复杂的交互效果,可以考虑通过触摸事件来实现。






博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。