记一次简单的防止页面加载过程中的抖动
今天在做项目的时候遇到一个问题:
一个很简单的页面,但是有一个问题:
如果网速比较慢,比如说我在Chrome里模拟3G网:
那么在图片加载的过程中,用户会感觉到明显的抖动,为了解决这个问题,可以在图片的外层加一个wrapper
来占位:
<div class="wrapper">
<swiper ref="mySwiper" :options="swiperOptions">
<swiper-slide>
<img class="swiper-img" src="@/assets/img/1.jpg" alt="">
</swiper-slide>
<swiper-slide>
<img class="swiper-img" src="@/assets/img/2.jpg" alt="">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</div>
并定义wrapper的样式:
宽度为100%父元素宽度,高度为0,下padding为31.25%。
为什么要这么做呢?
- 首先31.25%是根据图片的宽高比算出来的,图片宽:高 = 0.3125,因此如果图片的宽度为父元素宽度的100%,那么高度就应该为父元素宽度的31.25%(注意不是父元素高度的31.25%)
- 其次为什么选择把31.25% 放在 padding-bottom 而不是 height上呢? 这是因为,height 的百分比是相对父元素高度的,而padding四个方向的百分比都是相对父元素宽度的。
.wrapper {
//防抖
overflow: hidden; //好像这里没啥用
width: 100%;
height: 0;
padding-bottom: 31.25%;
background-color: #ccc;
}