根据第一张图片设置定义swiper其余图片的高度,解决lazy异步

文章描述了在移动端swiper组件中,如何处理图片展示的逻辑,特别是第一张图片需全屏显示,其余图片按比例填充。当图片宽高信息未知且使用懒加载时,可能出现异步加载严重的问题。通过JavaScript的Image对象预加载图片并计算高度,解决了这个问题。同时,采用CSS的object-fit:container实现图片居中和不足部分补白。
摘要由CSDN通过智能技术生成

背景: 需要要求M端swiper图片的展示逻辑根据第一张图定义其余图片的展示,第一张图宽高各100%展示,其余图片根据第一张来,高度或宽度不足的补白,当借口未返回图片宽高时,并且存在lazy加载的时候,图片太大lazy异步比较严重,以下解决lazy异步的问题:

getImgHeightByJs(){
      if(!firstImgPath) return firstImg.height(firstImg.eq(0).height());  // 图片路径不存在,取swiper中lazyload加载完成的
      let newImg = new Image;
      newImg.src = firstImgPath;  // 赋值图片路径
      newImg.onload = function(){
        if(newImg.complete && newImg.width) {  // width不存在说明图片加载失败是错误的图片
          let imgHeight = ($('body').width()/newImg.width)*newImg.height;
          firstImg.height(imgHeight)
        }
      };
 }

图片居中补白逻辑:
1.定义图片宽高
2.图片设置css object-fit: container;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Vue来说,根据当前屏幕大小来设置Swiper轮播的图片数有多种实现方式。以下是一种可能的实现方法: 首先,需要在Vue组件中引入Swiper库,并在`mounted`生命周期钩子中初始化Swiper实例。 ```javascript import Swiper from 'swiper'; export default { mounted() { const swiper = new Swiper('.swiper-container', { // Swiper的配置选项 // ... }); }, // ... } ``` 接下来,可以在Vue组件中使用计算属性来动态计算并设置Swiper轮播的图片数。 ```javascript export default { data() { return { screenSize: { width: 0, height: 0, }, images: ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'], }; }, mounted() { window.addEventListener('resize', this.updateScreenSize); this.updateScreenSize(); }, destroyed() { window.removeEventListener('resize', this.updateScreenSize); }, computed: { swiperParams() { const swiperSlidesPerPage = this.calculateSwiperSlidesPerPage(); return { // Swiper的其他配置选项 // ... slidesPerView: swiperSlidesPerPage, }; }, }, methods: { updateScreenSize() { this.screenSize.width = window.innerWidth; this.screenSize.height = window.innerHeight; }, calculateSwiperSlidesPerPage() { const screenWidth = this.screenSize.width; if (screenWidth < 768) { return 1; // 如果屏幕宽度小于768px,则每页显示一张图片 } else if (screenWidth < 992) { return 2; // 如果屏幕宽度介于768px和992px之间,则每页显示两张图片 } else { return 3; // 如果屏幕宽度大于等于992px,则每页显示三张图片 } }, }, // ... } ``` 这样,在Vue组件的模板中可以通过Swiper指令绑定使用计算属性的值来动态设置Swiper轮播的图片数。 ```html <template> <div class="swiper-container" v-swiper="swiperParams"> <div class="swiper-wrapper"> <div class="swiper-slide" v-for="image in images" :key="image"> <img :src="image" alt=""> </div> </div> <!-- Swiper的其他内容 --> </div> </template> ``` 通过上述方法,Vue可以根据当前屏幕大小来实现动态设置Swiper轮播的图片数,以适应不同屏幕尺寸的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值