elemen plus走马灯高度有固定值,做pc端轮播图无法根据窗口的宽度,实现高度自适应
解决办法:监听页面缩放
在走马灯外先给一个容器方便处理样式,给走马灯一个响应高度,用ref获取图片节点
<!-- 轮播图 -->
<div class="swiper">
<el-carousel class="el-carousel" :height="newHeight" :interval="3000" arrow="always">
<el-carousel-item v-for="item in bannerPic" :key="item">
<img ref="bannerImg" :src="item.url" style="width:100%;height:100%" alt="">
</el-carousel-item>
</el-carousel>
</div>
每次缩放都会触发监听事件,拿到图片高度的值,然后把图片高度的值给到走马灯,但是刚加载,不会触发监听事件,所以需要先给newHeight一个初始值,我这里是估了图片撑满时高度的值。
js:
// 轮播图图片数据
const bannerPic = reactive([
{ url: require("../assets/images/1654155115s6JpXe2Kew.png") },
{ url: require("../assets/images/1645781194NbHxdhxzYr.png") },
{ url: require("../assets/images/1636446752RtKZ5hRhKw.png") }
]);
// 获取轮播图片的节点
const bannerImg = ref()
// 轮播图自适应高度
const newHeight = ref('315px')
//监听屏幕缩放事件,
onMounted(() => {
window.onresize = () => {
newHeight.value = bannerImg.value[0].clientHeight + 'px'
}
css:
.swiper {
margin: 0 0 40px 0;
min-width: 1210px;
overflow: hidden;
.el-carousel {
width: 100%;
overflow: hidden;
:deep(.el-carousel__container) {
height: v-bind(newHeight);
}
:deep(.el-carousel__item) {
height: auto !important;
}
}
这个方法感觉并不是很完美,但是也能勉强解决问题,如果大家有更好的办法,欢迎来指教!