关键帧中的背景图片在Firefox或Internet Explorer中无法显示

3

我在我的网站上有几个动画,但我刚意识到它们甚至不会在Firefox或Internet Explorer中显示。我在关键帧内使用了background-image。我这样做是因为动画在不同百分比时有不同的图片。

为什么Firefox和Internet Explorer中的关键帧内不显示background-image,是否有方法使其正常工作?

1个回答

6
根据规范background-image 不是可过渡或可动画化的属性。但它似乎没有说明在转换或动画中使用时应该如何处理或处理什么。因此,每个浏览器似乎都在以不同的方式处理它。虽然Chrome(Webkit)正在显示背景图像,但Firefox和IE似乎什么也没做。
oli.jp的一篇文章中发现了以下引用,提供了一些有趣的信息:
尽管CSS背景和边框模块3级编辑者的草案在编写时表示“Animatable:no”,但在Chrome 19 Canary中出现了对CSS中交叉淡化图像的支持。在广泛支持到来之前,可以通过图像精灵和背景位置或不透明度来模拟这种效果。要动画显示渐变,它们必须是相同类型。
表面上看,Firefox和IE似乎正确处理它,而Chrome则不是。但事情并不那么简单。当处理背景图像的过渡和动画时,Firefox似乎在处理过渡时与处理动画时自相矛盾。在转换background-image时,它立即显示第二张图像(在片段中悬停第一个div),而在动画时,第二张图像根本不会显示出来(在片段中悬停第二个div)。
因此,结论是最好不要在关键帧中设置background-image。相反,我们必须像在oli.jp中指定的那样使用background-positionopacity

div {
  background-image: url(https://placehold.it/100x100);
  height: 100px;
  width: 100px;
  margin: 10px;
  border: 1px solid;
}
div:nth-of-type(1) {
  transition: background-image 1s ease;
}
div:nth-of-type(1):hover {
  background-image: url(https://placehold.it/100/123456/ffffff);
}
div:nth-of-type(2):hover {
  animation: show-img 1s ease forwards;
}
@keyframes show-img {
  to {
    background-image: url(https://placehold.it/100/123456/ffffff);
  }
}
<div></div>
<div></div>

如果您有多个图像在关键帧中应显示为不同的百分比,则最好在开始时将所有这些图像添加到元素上,并像下面的片段中的位置一样进行动画处理。 在 Firefox、Chrome 和 IE 中都是相同的工作方式

div {
  background-image: url(https://placehold.it/100x100), url(https://placehold.it/100/123456/ffffff);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: 0px 0px, 100px 0px;
  height: 100px;
  width: 100px;
  margin: 10px;
  border: 1px solid;
}
div:hover {
  animation: show-img 1s steps(1) forwards;
}
@keyframes show-img {
  to {
    background-position: -100px 0px, 0px 0px;
  }
}
<div></div>

或者,就像下面的代码片段一样。基本上,每个图像的大小与容器相同,因为 background-size 设置为 100% 100%,但只有一个图像在任何给定时间显示,因为它们与容器的大小相同。在 0%50% 之间,显示第一张图片,因为它位于 0px,0px(左上角),而第二张图片位于 100px,0px(超出右边框)。在 50.1% 处,第一张图片位于 -100px,0px(超出左边框),第二张图片位于 0px,0px,因此可见。

div {
  background-image: url(https://picsum.photos/id/0/367/267), url(https://picsum.photos/id/1/367/267);
  background-size: 100% 100%; /* each image will be 100px x 100px */
  background-repeat: no-repeat;
  background-position: 0px 0px, 100px 0px;
  height: 100px;
  width: 100px;
  margin: 10px;
  border: 1px solid;
  animation: show-img 5s ease forwards;
}
@keyframes show-img {
  0%, 50%{
    background-position: 0px 0px, 100px 0px; /* initially 1st image will be shown as it it as 0px 0px */
  }
  50.1%, 100% {
    background-position: -100px 0px, 0px 0px; /* at 50.1% 2nd image will be shown as it it as 0px 0px */
  }
}
<div></div>


1
是的,它帮了我很多!感谢您不断地为我提供帮助。 - Becky
1
@Becky:在关键帧中有几个不必要的 background-image: none这里是已修复的代码片段。 - Harry
我正在使用IE11。 - Becky
刚刚在跨浏览器测试网站上使用IE11和Edge进行了检查,两者都可以正常工作。 - Harry
1
@Becky:你应该使用图片的实际宽度进行位置计算。我之前使用了100像素是因为那是我的图片宽度。这里有一个宽度增加的示例,根据需要进行调整。 - Harry
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接