防止背景图像在更改时闪烁

Prevent background image flashing on change

我正在为按钮使用背景图片,然后在 :hover 上切换到另一个图片。

当第一个鼠标悬停在上面时发生切换时,背景颜色会短暂闪烁。 (我在这里将它设置为橙色,所以它更引人注目,它在白色背景下也是如此,或者如果我不设置背景颜色)。但是,它不会在随后的鼠标悬停时闪烁。

如何防止在页面加载和第一次鼠标悬停时背景颜色第一次闪烁?

https://codepen.io/ClayN/pen/EeeRyP

.backgroundbutton {
  background-image: url('http://www.BungalowSoftware.com/images/silver-background.jpg');
  width: 100px;
  height: 30px;
  background-color: orange;
}

.backgroundbutton:hover {
  background-image: url('http://www.BungalowSoftware.com/images/silver-background2.jpg')
}
<a class="backgroundbutton">hover over me</a>

由于悬停背景图片不会被预加载,所以它会显示闪烁效果,特别是对于较大的图片尺寸和较长的加载时间。

可以使用 CSS 精灵轻松修复,例如将 2 个背景图像合并为 1 个,并更改 :hover 上的 background-position,假设 new image 为 400px (200+200) 高度。

并且,不要设置任何 background-color 来停止页面加载时背景颜色的初始闪烁。此外,widthheight 不会应用于行内级别 a 标记,除非您将其更改为 display: inline-blockblock

.backgroundbutton {
  background: url("https://i.imgur.com/lrlOvEP.png") 0 0 no-repeat;
}

.backgroundbutton:hover {
  background-position: 0 -200px;
}
<a class="backgroundbutton">hover over me</a>

此外,渐变背景不需要任何图片,例如:

.backgroundbutton {
  background: linear-gradient(to right, #999, #fff);
}

.backgroundbutton:hover {
  background: linear-gradient(to right, #ccc, #fff);
}
<a class="backgroundbutton">hover over me</a>

使用多个背景加载两张图片,将第一张放在顶部,然后调整 background-size 以在悬停时显示另一张。在这种情况下,两张图片将首先加载,第二张将在悬停时准备就绪:

.backgroundbutton {
  background-image: 
   url('http://www.BungalowSoftware.com/images/silver-background.jpg'),
   url('http://www.BungalowSoftware.com/images/silver-background2.jpg');
  background-size:auto;
  width: 100px;
  height: 30px;
  background-color: orange;
}

.backgroundbutton:hover {
  background-size:0 0,auto;
}
<a class="backgroundbutton">  hover over me</a>