小程序--背景图片固定不上滑

时间:2024-04-05 11:17:11

要实现的功能如下图:(页面上滑的过程中轮播图片保持固定不动)
小程序--背景图片固定不上滑

实现过程:
1、首先还是要用到小程序的swiper组件
2、要实现背景图片不随页面滚动 可以用background-attachment:fixed 这个css属性实现
3、然后把轮播的图片设置到background-image里
4、问题:轮播图底部的面板指示点还是会随着页面滑动上去。解决办法就是把swiper自带的面板指示点隐藏(indicator-dots置为false) 然后自己写一个

---js-----
Page({
    data: {
        indicatorDots: false,
        autoplay: false,
        interval: 3000,
        duration: 500,
        imgUrls: [
            "background-image:url('../../images/bannerp1.jpg')",
            "background-image:url('../../images/bannerp2.jpg')",
            "background-image:url('../../images/bannerp3.jpg')"
        ],
        sliderIdx: 0
    },
    // 面板指示点的变化
    swiperChange: function (e) {
        let sliderIdx = e.detail.current
        this.setData({
            sliderIdx: sliderIdx
        })
    }
 })


----wxml-----
<view class="swiperMain">
    <swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" bindchange="swiperChange">
        <block wx:for="{{imgUrls}}" wx:key="{{index}}">
            <swiper-item>
                <view class="slide-image" style="{{item}}"></view>
            </swiper-item>
        </block>
    </swiper>
    <view class="dots">
        <block wx:for="{{imgUrls}}" wx:key="unique">
            <view class="{{index === sliderIdx ? 'active' : ''}}"></view>
        </block>
    </view>
</view>



-----wxss------
.swiperMain {
    position:relative;
}
.swiperMain .dots{
    position:fixed;
    top:780rpx;
    left:0px;
    right:0px;
    text-align: center;
    z-index: 1;
}
.swiperMain .dots view{
    width:20rpx;
    height:20rpx;
    background:rgba(0,0,0,0.4);
    display: inline-block;
    margin:0 10rpx;
    border-radius:20rpx;
}
.swiperMain .dots view.active{
    width:20rpx;
    height:20rpx;
    background:rgba(0,0,0,0.8);
}
swiper{
    height:840rpx;
}
.slide-image{
    width:750rpx;
    height:840rpx;
    background-repeat:no-repeat;
    background-position: center top;
    background-size:contain;
    background-attachment: fixed;
}