Carousel走马灯根据屏幕宽高大小自适应

HTML部分:

 <!--外层div通过ref获取高度-->
 <div class="M1container" ref="M1c">
       <el-carousel
        :height="M1Height + 'px'"
        :interval="2000"
       >
            <el-carousel-item v-for="item in 4" :key="item">
                <h3>{{ item }}</h3>
            </el-carousel-item>
  </el-carousel>
    </div>

JS部分:

export default {
    data(){
        return{
            M1Height:'',
        }
    },
    // 根据屏幕自适应轮播图大小
    mounted(){
        this.M1Height = this.$refs.M1c.clientHeight;
    }
}

原理就是通过ref获取走马灯外层容器可视区域的高度,然后再赋值给走马灯

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个 TypeScript 实现 Carousel走马灯高度自适应的示例代码: ```typescript interface CarouselItem { height: number; } class Carousel { private container: HTMLElement; private items: CarouselItem[]; private maxHeight: number; constructor(container: HTMLElement) { this.container = container; this.items = this.getCarouselItems(); this.maxHeight = this.getMaxItemHeight(); this.container.style.height = `${this.maxHeight}px`; window.addEventListener('resize', () => { this.updateCarouselHeight(); }); } private getCarouselItems(): CarouselItem[] { const items = this.container.querySelectorAll('.carousel-item'); return Array.from(items).map(item => { return { height: item.offsetHeight }; }); } private getMaxItemHeight(): number { return Math.max(...this.items.map(item => item.height)); } private updateCarouselHeight(): void { this.items = this.getCarouselItems(); this.maxHeight = this.getMaxItemHeight(); this.container.style.height = `${this.maxHeight}px`; } } const carouselContainer = document.querySelector('.carousel-container'); const carousel = new Carousel(carouselContainer); ``` 在这个示例中,我们定义了一个 Carousel 类,它接收一个 Carousel 容器的引用作为构造函数的参数。在构造函数中,我们获取 Carousel 容器中所有项目的高度,并计算最高项目的高度。然后,我们将 Carousel 容器的高度设置为最高项目的高度,并添加一个窗口大小调整事件的监听器,以便在窗口大小发生变化时更新 Carousel 容器的高度。 在 Carousel 类中,我们还定义了三个私有方法: - `getCarouselItems()`:获取 Carousel 容器中所有项目的高度,并返回一个 CarouselItem 数组。 - `getMaxItemHeight()`:计算 Carousel 容器中所有项目的最大高度,并返回该值。 - `updateCarouselHeight()`:在窗口大小发生变化时更新 Carousel 容器的高度,包括重新计算所有项目的高度和最大高度,并将 Carousel 容器的高度设置为最大高度。 请注意,我们使用了 TypeScript 中的接口来定义 CarouselItem 类型,以确保每个项目具有 `height` 属性。 通过这种方式,我们可以实现一个高度自适应Carousel 走马灯组件,并且它可以与任何 TypeScript 或 JavaScript 应用程序一起使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值