简体   繁体   中英

CSS opacity transition doesn't respect overlay opacity during animation

I have a div that contains a single div that acts as an overlay, along with another div that contains some images. The overlay has an opacity so that the images can be seen, but text can be still be read.

However, when I animate the opacity of the image, it ignores the overlay during the animation, until it is finished.

He's the code:

HTML

<div class="container">
  <div class="overlay"></div>
  <div class="image-container">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">
  </div>
</div>

CSS

.container {
    position: absolute;
    top: 0;
    z-index: 1;
    height: 100%;
    overflow: hidden;
    background-color: yellow;
}

.overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0px;
    opacity: 0.78;
    background-color: rgb(245, 245, 245);
}

JavaScript

var image = document.getElementsByTagName("IMG")[0];
image.style.opacity = 0;

setTimeout(function() {
    image.style.transition = "opacity 3s linear";
    image.style.opacity = 1;
}, 1000);

I also have a jsfiddle example:

https://jsfiddle.net/ygqov8t4/

I have tested this in Chrome, Firefox, and Safari on Mac. All browser have the same behaviour, so maybe this is by design?

I have tried doing this using JavaScript, but I was not able to get the animation functioning, and I am concerned about performance because this is going to be run on a lot (100+) images.

image.onload = function() {
    var self = this;
    for (var i = 0; i < 1000; i++) {
        setTimeout(function() {
            self.style.opacity = i/1000;
        }, i);
    }
}

Try forcing the overlay to be above the image by setting its z-index to 1

.overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0px;
    opacity: 0.78;
    background-color: rgb(245, 245, 245);
    z-index: 1;
}

https://jsfiddle.net/05pwwtm7/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM