首页 > 解决方案 > 在所有现代浏览器中工作相同的背景图像之间的转换?

问题描述

我正在尝试使用 CSS 淡入/淡出背景图像。

transitions为此目的使用 CSS。

-webkit-transition: all 0.9s ease-in-out 0s;
  -moz-transition: all 0.9s ease-in-out 0s;
  -ms-transition: all 0.9s ease-in-out 0s;
  -o-transition: all 0.9s ease-in-out 0s;
  transition: all 0.9s ease-in-out 0s;

上面的代码在 Chrome 中运行良好,但在 Firefox 中根本不起作用!

一个工作的小提琴

单击“Apple”文本以查看 chrome 中的过渡。

有人可以就这个问题提出建议吗?

标签: css

解决方案


您可以考虑伪元素以创建不同的图层,然后您可以将opacity其用于淡入淡出:

$('.box').click(function() {
  $(this).toggleClass('animate');
});
.box {
  margin: 10px;
  width: 200px;
  height: 200px;
  background: url(https://picsum.photos/200/300?image=1069);
  position: relative;
  z-index: 0;
}

.box:before,
.box:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 1;
}

.box:before {
  background: url(https://picsum.photos/200/300?image=1045);
  transition: 0.5s;
}

.box:after {
  background: url(https://picsum.photos/200/300?image=1049);
  transition: 0.5s 0.5s;
}

.box.animate::before {
  opacity: 0;
  transition: 0.5s 0.5s;
}
.box.animate::after {
  opacity: 0;
  transition: 0.5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">

</div>

如果您想要另一种可以播放的动画background-size和多个背景:

.box {
  margin: 10px;
  width: 200px;
  height: 200px;
  background-image: 
    url(https://picsum.photos/200/200?image=1069),
    url(https://picsum.photos/200/200?image=1045),
    url(https://picsum.photos/200/200?image=1049),
    url(https://picsum.photos/200/200?image=1051);
 background-size:100% 100%;
 background-position:center;
 background-repeat:no-repeat;
}
.box:hover {
  animation:change 2s linear forwards;
}
@keyframes change {
  0%  {background-size:100% 100%,100% 100%,100% 100%,100% 100%;}
  25% {background-size:0    0   ,100% 100%,100% 100%,100% 100%;}
  50% {background-size:0    0   ,0    0   ,100% 100%,100% 100%;}
  75% {background-size:0    0   ,0    0   ,0    0   ,100% 100%;}
  100%{background-size:0    0   ,0    0   ,0    0   ,0    0;}
}
<div class="box">

</div>

您还可以调整background-position以创建不同的过渡方式:

.box {
  margin: 10px;
  width: 200px;
  height: 200px;
  background-image: 
    url(https://picsum.photos/200/200?image=1069),
    url(https://picsum.photos/200/200?image=1045),
    url(https://picsum.photos/200/200?image=1049),
    url(https://picsum.photos/200/200?image=1051);
 background-size:100% 100%;
 background-position:left;
 background-repeat:no-repeat;
}
.box:hover {
  animation:change 2s linear forwards;
}
@keyframes change {
  0%  {background-size:100% 100%,100% 100%,100% 100%,100% 100%;}
  25% {background-size:0    100%,100% 100%,100% 100%,100% 100%;}
  50% {background-size:0    100%,0    100%,100% 100%,100% 100%;}
  75% {background-size:0    100%,0    100%,0    100%,100% 100%;}
  100%{background-size:0    100%,0    100%,0    100%,0    100%;}
}
<div class="box">

</div>


推荐阅读