微信小程序轮播图(适配机型)

1:wxss样式:

/* 页面显示图片的框 */
.showTableBox {
    position: relative;
    width: 100%;
    height: 180px;
    overflow: hidden;
}

/* img图片所在的父元素盒子,有几张img,width就设置百分之几百 */
.slideshowImgBox {
    position: absolute;
    z-index: 1;
    width: 500%;
    height: 100%;
}

/* img width设置为: 100% / 图片总数 的百分比 */
.slideshowImgBox image {
    width: 20%;
    height: 100%;
    float: left;
}
/* 下方小圆点样式*/
.circleBox {
    width: 100%;
    position: absolute;
    bottom: 10px;
    justify-content: center;
}

.circle {
    width: 5px;
    height: 5px;
    border-radius: 50%;
    background-color: #F5F5F5;
    margin: 0 5px;
    z-index: 999;
}

.circleActive {
    background-color: #BF360C;
}

其实到这里适配就完成啦,下面是怎么手写一个轮播图哈哈
2:js代码:

page({
  data: {
        leftNum: 0,//type为number的偏移量,方便计算
        imgLeft: "0", //偏移量,
        screenWidth: 0, //屏幕width
        changCircleIndex: 0, //对应圆球的下标,css根据页面下标显示对应class
        slideshowImgs: ["../images/beiJing.jpg", "../images/chengDu.jpg",
            "../images/shangHai.jpg", "../images/chongQing.jpg", "../images/beiJing.jpg"
        ],
},
 onLoad: function (options) {
        this.setData({
            screenWidth: wx.getSystemInfoSync().windowWidth //获取屏幕宽度
        })
        this.imageCarousel()
    },

    imageCarousel: function () {
        let imgOverallWidth = this.data.screenWidth * (this.data.slideshowImgs.length - 1)
        let timer = setInterval(() => {
            this.data.imgLeft = `${this.data.leftNum -= this.data.screenWidth}px`
            this.setData({
                imgLeft: this.data.imgLeft,
                changCircleIndex: -(this.data.leftNum / this.data.screenWidth)
            })
            if (this.data.leftNum === -imgOverallWidth) {
                this.setData({
                    changCircleIndex: 0,
                    leftNum: 0,
                    imgLeft: `${this.data.leftNum}px`
                })
            }
        }, 3000)
    },
})

3:wxml代码:

<view class="photo">
	<view class="photoFixedBox">
		<view class="showTableBox">
			<view class="slideshowImgBox" style="left:{{imgLeft}};">
<!--这里列表渲染的图片一共五张,第一张和最后一张是同一张图,防止轮播时出现白屏 -->
				<image wx:for="{{slideshowImgs}}" src="{{item}}"></image>
			</view>
			<view class="circleBox flex">
		<!-- {{changCircleIndex === index ? 'circleActive' : ''}}"是动态class,根据index来改变圆点颜色  -->
				<view wx:for="{{slideshowImgs.length-1}}" class="circle {{changCircleIndex === index ? 'circleActive' : ''}}"></view>
			</view>
		</view>
		<view class="photoClassifyBigBOx">
			<view class="imgClassifyBox flex"  wx:for="{{imgClassify}}"><text>{{item}}</text></view>
		</view>
	</view>
</view>

以上就是整个轮播图的实现啦,圆点的变色显示index根据图片left的偏移量距离来计算:偏移量 / 显示框的宽度,
其实微信小程序有swiper组件,使用也是很方便的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值