资源请求和加载都是需要时间的。对于图片一些内容的展示,当图片没有加载出来时。容器高为零,那么下面的dom元素会上移。当图片加载后,会容器撑开。这样会造成页面的重排。
为了解决以上问题我们可以使用padding的百分比占位实现(或者margin)。
让我们把padding这是为百分比时。他百分比对应的是父级的宽的比(W3C规定)
我们就实现了占位。我们需要占位的空间添加内容,这时我们就需要定位属性或者浮动来解决(当父级高度设置为0的时候有惊喜)
* {
margin: 0;
padding: 0;
list-style: none;
}
.wrapper {
/* 弹性盒子。换行处理。内容居中 */
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.box {
position: relative;
width: 25%;
padding-bottom: 25%;
background-color: #eee;
float: left;
/* background-color: green; */
margin-left: 10px;
margin-bottom: 10px;
}
.box img{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
CSS基本样式,我们可以用定时器模拟图片的加载过程。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.wrapper {
/* 弹性盒子。换行处理。内容居中 */
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.box {
position: relative;
width: 25%;
padding-bottom: 25%;
background-color: #eee;
float: left;
/* background-color: green; */
margin-left: 10px;
margin-bottom: 10px;
}
.box img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<script>
let box = document.getElementsByClassName('box');
let imgArr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
let index = 0;
let timer = setInterval(() => {
let img = `<img src="./images/${index}.jpg" />`
box[index].innerHTML = img;
index++;
if (index == imgArr.length) {
clearInterval(timer)
}
}, 1000)
</script>
</body>
</html>
文章有点老~不过利于理解