SVG 背景在悬停时闪烁一次

SVG Background Flickering Once on Hover

我有一个带有 svg 背景的按钮,它的悬停也有一个 svg 背景。当我在页面加载后第一次将鼠标悬停在它上面时,会出现闪烁,但随后的任何悬停都不会闪烁。我认为这可能是一个加载问题,但即使我在页面上独立加载两个图像或预加载图像,这种闪烁仍然会发生,所以它不是加载问题。怎么回事?

.minus{
    background: url(https://www.svgrepo.com/show/294589/shuffle-random.svg);
background-size: cover;
    border: 0;
    display: block;
    height: 20px;
    width: 20px;
}

.minus:hover{
    background: url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
}
<button class="minus">

这是因为未加载隐藏元素/资产(不活动的选择器或 display: none,等等)。您必须手动预加载它。

这里有一些想法:

Note: The server https://www.svgrepo.com/ sometimes responds with 403 Forbidden. So you probably see no images. (See console)

使用 CSS

预加载

.minus {
  background: url(https://www.svgrepo.com/show/294589/shuffle-random.svg);
  background-size: cover;
  border: 0;
  display: block;
  height: 20px;
  width: 20px;
}

.minus:hover {
  background: url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
}

body:after {
  /* display: none -- does not work anymore due to latest optimizations.*/
  display: block;
  overflow: hidden;
  width: 0;
  height: 0;
  content: url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
}
<button class="minus"></button>

这只是其中一种方法。这可能取决于您的框架。您也可以在 JavaScript 中执行此操作(加载图像)。或者有不同的想法:使用平铺精灵作为(一个)图像,只需在悬停时移动背景位置。或者同时加载两者。

使用精灵

.minus {
  background: 
    url(https://www.svgrepo.com/show/294589/shuffle-random.svg),
    url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
  background-size: cover;
  background-position: 0, 20px;
  background-repeat: no-repeat;
  border: 0;
  display: block;
  height: 20px;
  width: 20px;
}

.minus:hover {
  background-position: 0;
}
<button class="minus"></button>

预加载 HTML

中的图像

.minus {
  background: url(https://www.svgrepo.com/show/294589/shuffle-random.svg);
  background-size: cover;
  border: 0;
  display: block;
  height: 20px;
  width: 20px;
}

.minus:hover {
  background: url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
}

#preload {
  /* In this case / context display hidden works. */
  display: none;
}
<div id="preload">
  <img src="https://www.svgrepo.com/show/240096/shuffle-random.svg">
</div>

<button class="minus"></button>

预加载 JavaScript

中的图像

[
  'https://www.svgrepo.com/show/294589/shuffle-random.svg',
  'https://www.svgrepo.com/show/240096/shuffle-random.svg',
].forEach((imageUrl) => {
  new Image().src = imageUrl;
});
.minus {
  background: url(https://www.svgrepo.com/show/294589/shuffle-random.svg);
  background-size: cover;
  border: 0;
  display: block;
  height: 20px;
  width: 20px;
}

.minus:hover {
  background: url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
}
<button class="minus"></button>

使用以下关键字搜索网络:css 背景图片悬停闪烁预加载等