【问题标题】:Prevent background image flashing on change防止背景图像在更改时闪烁
【发布时间】:2018-09-17 05:55:55
【问题描述】:

我正在为按钮使用背景图片并在: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>

【问题讨论】:

  • 如何设置background-color: transparent ??
  • @AXL 不起作用。我只是得到页面颜色(透明按钮后面的任何内容。

标签: css background-image


【解决方案1】:

使用多个背景加载两张图片并将第一张放在顶部,然后调整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>

【讨论】:

    【解决方案2】:

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

    它可以通过使用 CSS sprites 轻松修复,例如将 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>

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 2020-08-17
      • 2017-08-24
      • 2018-02-09
      • 2013-04-17
      • 2019-05-23
      • 1970-01-01
      • 2014-03-19
      相关资源
      最近更新 更多