关键帧中的背景图像不会显示在Firefox或Internet Explorer中

Bec*_*cky 3 css firefox internet-explorer css3 css-animations

我在我的网站上有几个动画,我刚才意识到甚至没有出现在Firefox或Internet Explorer中.我有background-image关键帧内.我这样做是因为我在动画中有不同百分比的不同图像.

为什么不在background-imageFirefox和Internet Explorer中的关键帧内显示,是否有办法使其工作?

Har*_*rry 5

根据规格,background-image不是动画或可转换的属性.但是当它被用作过渡或动画的一部分时,它似乎没有说明处理应该是什么或如何.因此,每个浏览器似乎都以不同的方式处理它.虽然Chrome(Webkit)正在显示背景图像,但Firefox和IE似乎什么都不做.

在oli.jp的文章中找到的以下引用提供了一些有趣的信息:

虽然CSS背景和边框模块3级编辑的草稿在撰写本文时对背景图像说"动画:否",但在Chrome 19 Canary中出现了对CSS中交叉淡化图像的支持.在广泛的支持到来之前,这可以通过图像精灵和背景位置或不透明度伪造.要为渐变设置动画,它们必须是相同的类型.

从表面上看,似乎Firefox和IE正在正确处理它,而Chrome则不然.但是,它并非如此简单.当涉及它如何处理背景图像上的转换而不是动画时,Firefox似乎自相矛盾.在转换时background-image,它立即显示第二个图像(片段中hover的第一个div),而在制作动画时,第二个图像根本不显示(片段中hover的第二个div).

因此,结论是不设置 background-image 内部关键帧更好.相反,我们必须使用background-positionopacity喜欢指定@ oli.jp.

div {
  background-image: url(http://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(http://placehold.it/100/123456/ffffff);
}
div:nth-of-type(2):hover {
  animation: show-img 1s ease forwards;
}
@keyframes show-img {
  to {
    background-image: url(http://placehold.it/100/123456/ffffff);
  }
}
Run Code Online (Sandbox Code Playgroud)
<div></div>
<div></div>
Run Code Online (Sandbox Code Playgroud)


如果你有多个图像应该在关键帧内以不同的百分比显示,那么最好在开始时在元素上添加所有这些图像,并在下面的代码片段中设置其位置的动画.这在Firefox,Chrome和IE中的工作方式相同.

div {
  background-image: url(http://placehold.it/100x100), url(http://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;
  }
}
Run Code Online (Sandbox Code Playgroud)
<div></div>
Run Code Online (Sandbox Code Playgroud)

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

div {
  background-image: url(http://lorempixel.com/100/100/nature/1), url(http://lorempixel.com/100/100/nature/2);
  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 10s 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 */
  }
}
Run Code Online (Sandbox Code Playgroud)
<div></div>
Run Code Online (Sandbox Code Playgroud)