我的网站上有几个动画,我刚刚意识到它们甚至没有显示在 Firefox 或 Internet Explorer 中。我有background-image
在关键帧内。我这样做是因为我在动画中具有不同百分比的不同图像。
为什么不background-image
在 Firefox 和 Internet Explorer 的关键帧内显示,有没有办法实现这一点?
根据specs, 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-position
or opacity
就像@oli.jp 指定的那样。
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%
to 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)