评论
双Swpier实现首页轮播图和高斯模糊背景同步滚动

双Swpier实现首页轮播图和高斯模糊背景同步滚动

见面的意义是为了宣泄不见面时积压在心里浓浓的爱意

​不见面的时候除了好好生活就是在期待与你的见面

双Swpier实现首页轮播图和高斯模糊背景同步滚动

国庆期间有大佬阅读到之前写的《微信小程序文章详情页模版——CSS控制渐变图片高斯模糊》文章,想在首页的轮播图上加载该效果,同时能满足以下需求

  1. 轮播图自动滚动,背景也能随着滚动
  2. 手动滑动轮播图,背景也可以跟着变化

预览

思路

只需要使用Swpier的bindchange事件获取current值,将值复制给背景即可

实践

通过学习我们需要建立2个Swpier,一个作为首页的正常显示,另一个作为背景;此外还需要一个容器来做渐变的高斯模糊

wxml

<!--index.wxml-->
<view class="index-view">
  <!-- 背景轮播 -->
  <swiper class="index-bg" autoplay="{{autoplay_index}}" current="{{current}}">
    <block wx:for="{{background}}" wx:key="index">
      <swiper-item>
        <image src="{{item}}" class="fengrui-img"></image>
      </swiper-item>
    </block>
  </swiper>
​
  <!-- 高斯模糊图层 -->
  <view class="index-blur"></view>
​
  <!-- 轮播图组件 -->
  <swiper class="idnex-swpier idnex-swpier-top" indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" bindchange="bindchange">
    <block wx:for="{{background}}" wx:key="index">
      <swiper-item>
        <image src="{{item}}"></image>
      </swiper-item>
    </block>
  </swiper>
</view>

wxss

/**index.wxss**/
.index-view {
  height: 600rpx;
  width: 100%;
  position: relative;
  overflow: hidden;
}
​
.index-blur {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  backdrop-filter: blur(18px);
  background-image: linear-gradient(to bottom,
      rgba(0, 0, 0, 0) 0%,
      rgba(150, 150, 150, 0.1) 20%,
      rgba(255, 255, 255, 0.2) 40%,
      rgba(255, 255, 255, 0.6) 60%,
      rgb(255, 255, 255) 100%);
}
​
.idnex-swpier {
  height: 300rpx;
}
​
.idnex-swpier-top {
  margin-top: 200rpx;
  padding: 0 80rpx;
}
​
.swiper-item {
  height: 300rpx
}
​
.index-bg {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}
​
.fengrui-img{
  width: 100%;
  height: 100%;
}

js

// index.js
// 获取应用实例
const app = getApp()
​
Page({
  data: {
    background: ['https://cdn.frbkw.com/wp-center/uploads/2023/09/20230911163221208.jpg', 'https://cdn.frbkw.com/wp-center/uploads/2023/08/20230807112816440.jpg', 'https://cdn.frbkw.com/wp-center/uploads/2023/09/20230907144802855.jpg'],
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    autoplay_index:false,
    interval: 2000,
    duration: 500,
​
    // 轮播图片index
    current:0,
  },
​
  // 获取轮播图组件当前index
  bindchange(e){
    console.log(e.detail.source)
    this.setData({
      current:e.detail.current,
    })
  }
})

json

{
  "usingComponents": {},
  "navigationStyle":"custom"
}

填坑

Swpier的好处就是他背景在交替时候有完整的过渡动画,这里还有一个坑

就是正常显示的轮播图是可以选择是否自动轮播,而做背景不能开起自动轮播,因为开起之后用户手动滑动就会导致2个swpier滚动不不同步

在微信开放文档也提到current,他最好通过source判断是自动滚动还是用户手动行为在传值;而我们的案例上他是不停替换current的值,之前还会纠结这个问题,回头想想现在的手机性能又不是带不动,而且首页不是打开几天几夜在关闭

源码

https://yinfengrui.lanzoub.com/iVyIk1b7m6ha

总结

啊对对对