Element.ui 【走马灯】根据屏幕的宽高自适应大小

1、首先贴出element.ui走马灯组件的class,可以直接赋值修改:(如果有内联样式记得用!important

/* 走马灯每个item */
.el-carousel__item{
    
    }

/* 走马灯当前展示的item */
.is-active{
    
    }

/* 走马灯item的容器 */
.el-carousel__container{
    
    }

/* 整个走马灯的容器,包含指示器等其它组件在内 */
.el-carousel{
    
    }

2、走马灯动态适应屏幕的宽高:(具体细节可以根据需求自己调整)

1)首先修改item的宽:

.el-carousel__item{
    
    
	width: 80%;
	left: -15%;
}

2)自适应高度:

  • 在item标签中添加动态的item属性::height=" bannerHeight + 'px' "

  • 在Vue的data中添加上述的bannerHeight属性,和screenWidth属性

    bannerHeight : 100,//图片父容器的高度
    screenWidth :0,//屏幕的宽度
    
  • 添加方法来动态为data中的这两个值赋值:

    • 在mounted中获取到屏幕的宽并赋值给screenWidth,
    mounted:function() {
          
          
    	this.screenWidth =  window.innerWidth;
    	this.setSize();
    	window.onresize = () =>{
          
          
    		this.screenWidth =  window.innerWidth;
          	this.setSize();
        };
    },
    
    • 在methods方法中动态计算高度:
    methods:{
          
          
    	setSize:function () {
          
          
    	   	// 通过屏幕宽度(图片宽度)计算高度
    		this.bannerHeight = 400 / 1920 * this.screenWidth;
    	},
    }
    

3、贴出完整代码:

<div id="app">
	<template>
		<el-carousel :interval="4000" type="card" arrow="never" :height="bannerHeight + 'px'" :autoplay="autoplay" ref="carousel">
			<el-carousel-item v-for="item in carouseData" :key="item.id" :id="item.id">
				<img class="element-img" alt="" :src="item.url">
			</el-carousel-item>
		</el-carousel>
	</template>
</div>
var vm = new Vue({
    
    
	el:"#app",
	data(){
    
    
		return:{
    
    
			bannerHeight : 100,//图片父容器的高度
			screenWidth :0,//屏幕的宽度
		}
	},
	mounted:{
    
    
		this.screenWidth =  window.innerWidth;
		this.setSize();
   		window.onresize = () =>{
    
    
 			this.screenWidth =  window.innerWidth;
          	this.setSize();
        };
	},
	methods:function(){
    
    
		setSize:function () {
    
    
		   	// 通过屏幕宽度(图片宽度)计算高度
			this.bannerHeight = 400 / 1920 * this.screenWidth;
		},
	}
})

猜你喜欢

转载自blog.csdn.net/weixin_44296929/article/details/108508450
今日推荐