一、基本需求
浏览器窗口改变时,轮播图的图片要等比例缩放
二、实现思路
1. 编写基本的 HTML 结构
2. 定义变量 swiperImageList 接收 API 传入的轮播图数据,并给轮播图绑定数据
3. 定义一个变量 swiperHeight 用来计算轮播图容器的高度,当浏览器窗口改变时,更改这个变量的值
4. 计算 swiperHeight 分为两种情况
a ) 初始化:swiperHeight 等于第一张图片的高度
b ) 切换图片时:swiperHeight 等于当前图片的高度
三、代码
<template>
<swiper
class="swiper"
:style="{
height: swiperHeight + 'px'
}"
circular
:indicator-dots="true"
:autoplay="true"
:disable-touch="true"
:interval="3000"
@change="swiperChange"
:current="swipertCurrent"
:duration="500"
>
<swiper-item v-for="(item, index) in swiperImageList" :key="index">
<view class="swiper-item">
<img :id="'wrap' + index" mode="widthFix" :src="item.imageUrl" alt="" />
</view>
</swiper-item>
</swiper>
</template>
<script>
export default {
name: 'SwiperPc',
data() {
return {
swiperImageList: [],
swiperHeight: 0,
swipertCurrent: 0 //顶部轮播图 当前下标
}
},
mounted() {
//1.初始化轮播图容器高度为第一张图片的高度
this.initImageHeight()
//2.如果轮播图只有一张图片那么容器高度等于更改浏览器窗口时,第一张图片的高度,如果不是只有一张图片,会调用changeSwiperHeight进行自适应
if (this.swiperImageList.length === 1) {
// 监听窗口大小变化
window.addEventListener('resize', this.initImageHeight)
} else {
// 监听窗口大小变化
window.addEventListener('resize', this.changeSwiperHeight)
}
},
beforeDestroy() {
if (this.swiperImageList.length === 1) {
// 在组件销毁前移除窗口大小变化的监听器
window.removeEventListener('resize', this.initImageHeight)
} else {
// 监听窗口大小变化
window.removeEventListener('resize', this.changeSwiperHeight)
}
},
methods: {
//根据图片的URL计算图片的高度和宽度
getImageSize(url) {
return new Promise(function (resolve, reject) {
let image = new Image()
image.onload = function () {
resolve({
height: image.height,
width: image.width
})
}
image.onerror = function () {
reject(new Error('图片加载失败'))
}
image.src = url
})
},
async initImageHeight() {
const imgElement = document.getElementById('wrap0')
//1.如果图片加载出来了就使用第一张图片的高度
if (imgElement.offsetHeight) {
this.swiperHeight = imgElement.offsetHeight
} else {
//2.没加载出来就计算
let imageData = await this.getImageSize(imgElement.src)
let clientWidth = document.documentElement.clientWidth > 1000 ? document.documentElement.clientWidth : 1000
let zoom = clientWidth / imageData.width //浏览器宽度/图片原始宽度为缩放比率
this.swiperHeight = imageData.height * zoom //图片原始高度乘以缩放比率则相当于等比例缩放
}
},
changeSwiperHeight() {
const imgElement = document.getElementById('wrap' + this.swipertCurrent)
if (imgElement) {
this.swiperHeight = imgElement.offsetHeight
}
},
swiperChange(e) {
//获取当前轮播图播放的图片索引
this.swipertCurrent = e.detail.current
}
}
}
</script>