在Vue項目開發中,發現使用Element的走馬燈功能實例中
<template> <div class="block"> <span class="demonstration">默認 Hover 指示器觸發</span> <el-carousel height="150px"> <el-carousel-item v-for="item in 4" :key="item"> <h3 class="small">{{ item }}</h3> </el-carousel-item> </el-carousel> </div> <div class="block"> <span class="demonstration">Click 指示器觸發</span> <el-carousel trigger="click" height="150px"> <el-carousel-item v-for="item in 4" :key="item"> <h3 class="small">{{ item }}</h3> </el-carousel-item> </el-carousel> </div> </template> <style> .el-carousel__item h3 { color: #475669; font-size: 14px; opacity: 0.75; line-height: 150px; margin: 0; } .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } img{ width:100%; } </style>
由於img的寬度設置了100%,所以高度會根據圖片來自動調整,但當瀏覽器的大小發生改變,會出現圖片下面出現空白現象,如果固定img的高度,那么圖片就可以會隨瀏覽器的變化發生變形。
圖片下面出現空白現象
圖片就可以會隨瀏覽器的變化發生變形
這個時候可以通過動態設置父級容器的高度來解決這個問題,代碼如下
<template> <div id="banner"> <!--動態將圖片輪播圖的容器高度設置成與圖片一致--> <el-carousel :height="bannerHeight + 'px'" > <!--遍歷圖片地址,動態生成輪播圖--> <el-carousel-item v-for="item in img_list" :key="item"> <img :src="item" alt=""> </el-carousel-item> </el-carousel> </div> </template> <script> export default { name: "Banner", data(){ return{ // 圖片地址數組 img_list:[ "/static/image/111.png", "/static/image/222.png", "/static/image/333.png", "/static/image/444.png", ], // 圖片父容器高度 bannerHeight :1000, // 瀏覽器寬度 screenWidth :0, } }, methods:{ setSize:function () { // 通過瀏覽器寬度(圖片寬度)計算高度 this.bannerHeight = 400 / 1920 * this.screenWidth; }, }, mounted() { // 首次加載時,需要調用一次 this.screenWidth = window.innerWidth; this.setSize(); // 窗口大小發生改變時,調用一次 window.onresize = () =>{ this.screenWidth = window.innerWidth; this.setSize(); } } } </script> <style scoped> .el-carousel__item h3 { color: #475669; font-size: 14px; opacity: 0.75; line-height: 300px; margin: 0; } .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } img{ /*設置圖片寬度和瀏覽器寬度一致*/ width: 100%; height: inherit; } </style>