在加載頁面資源時,可能會延遲,這時會出現頁面抖動,通過以下方法自動撐開空白區域,提升用戶體驗。
overflow: hidden;
width: 100%;
height: 0;
padding-bottom: 高/寬%;
完整代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
body {
width: 300px;
}
div {
overflow: hidden;
width: 100%;
height: 0;
/* padding-bottom: (高/寬)*100% */
/* padding-bottom: (200/300)*100% */
padding-bottom: 67%;
background-color: #eee;
}
img {
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div>
<img src="" alt="">
</div>
<p>test</p>
<script>
let img = document.getElementsByTagName('img')[0];
// 模擬3秒后獲取圖片src
setTimeout(()=>{
img.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2902605362,3026849888&fm=26&gp=0.jpg'
},3000)
</script>
</body>
</html>
三秒后: