没有调整大小的CSS背景图像转换

时间:2015-07-20 13:01:11

标签: css3 background-image transition

请看一下here

transition: background-image 2s;

背景图片的大小不同,过渡效果也很难看。是否可以在不使用CSS调整大小的情况下淡化图像?

1 个答案:

答案 0 :(得分:1)

您可以使用两个元素,一个是第一个背景,另一个是第二个背景。定位元素,使其中一个元素位于另一个元素之上,并将元素的不透明度转换为顶部。



var current = 0;
setInterval(function() {
    document.querySelector('.image2').style.opacity = (current++ % 2);
}, 3000);

.image1,.image2 {
    width: 600px;
    height: 370px;
    border: 1px solid;
    background-color: white;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    transition: opacity 2s;
}
.image1 {
    background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/512px-HTML5_logo_and_wordmark.svg.png');
}
.image2 {
    margin-top: -370px;
    background-image: url('https://upload.wikimedia.org/wikipedia/commons/8/83/CSS-Logo.png');
}

<div class="image1"></div>
<div class="image2"></div>
&#13;
&#13;
&#13;

或者,使用CSS animation代替JavaScript:

&#13;
&#13;
@keyframes fade {
  0% { opacity: 0; }
  10% { opacity: 0; }
  40% { opacity: 1; }
  60% { opacity: 1; }
  90% { opacity: 0; }
  100% { opacity: 0; }
}
.image1,.image2 {
    width: 600px;
    height: 370px;
    border: 1px solid;
    background-color: white;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
}
.image1 {
    background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/512px-HTML5_logo_and_wordmark.svg.png');
}
.image2 {
    margin-top: -370px;
    background-image: url('https://upload.wikimedia.org/wikipedia/commons/8/83/CSS-Logo.png');
    animation: fade 5s linear infinite;
}
&#13;
<div class="image1"></div>
<div class="image2"></div>
&#13;
&#13;
&#13;