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

本文介绍如何使用 Element UI 的走马灯组件实现动态适应屏幕宽高的效果,包括修改 CSS 类、添加动态高度属性、计算屏幕宽度和高度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
		},
	}
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你好像很好吃a

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值