初次进入页面,资源未加载
html
<div class="imgBox imgBox0"></div>
...
<style>
.imgBox {
width: 100px;
height: 100px;
background-repeat: no-repeat;
cursor: pointer;
margin-bottom: 40px;
}
.imgBox0 {
background-image: url('./images/bg_def.png');
background-size: 100% 100%;
}
.imgBox0:hover {
background-image: url('./images/bg_act.png');
}
</style>
- 在初次进入页面时,图片资源只加载了 bg_def.png

- 在鼠标悬浮时,才加载 bg_act.png,并且有一个很短暂的闪动效果

为了消除闪动效果,有以下几种解决方式
双背景图
- 给元素配置两个背景图,这样两个图片资源都会预先加载出来
- 设置样式,默认状态时设置 bg_act.png 大小为 0,悬浮状态时设置 bg_def.png 大小为 0
html
<style>
.imgBox1 {
background-image: url('./images/bg_def.png'), url('./images/bg_act.png');
background-size: 100% 100%, 0 0;
}
.imgBox1:hover {
background-size: 0 0, 100% 100%;
}
</style>

伪元素
- 给元素添加伪元素,伪元素的背景图也会预先加载
- 设置样式,伪元素与初始元素完全重叠,背景图设置为 def_act.png,默认透明,悬浮时显示
html
<style>
.imgBox2 {
background-image: url('./images/bg_def.png');
background-size: 100% 100%;
position: relative;
}
.imgBox2::after {
content: "";
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background-image: url('./images/bg_act.png');
background-size: 100% 100%;
opacity: 0;
}
.imgBox2:hover::after {
opacity: 1;
}
</style>


link 的 preload 设置
- 使用 link 的 preload 属性,指定想要预先加载的资源
html
<head>
<title>test</title>
<!-- 必须指定 as="image",否则浏览器可能以低优先级 fetch 处理 -->
<link rel="preload" href="./images/bg_act.png" as="image">
</head>
...
<style>
.imgBox3 {
background-image: url('./images/bg_def.png');
background-size: 100% 100%;
}
.imgBox3:hover {
background-image: url('./images/bg_act.png');
background-size: 100% 100%;
}
</style>

雪碧图
- 小体积图片资源可使用雪碧图加载,悬浮时采用不同的定位
html
<style>
.imgBox4 {
background-image: url('./images/bg_sprite.png');
background-size: 230px 100px;
background-position: 0 center;
}
.imgBox4:hover {
background-position: -130px center;
}
</style>
