简体   繁体   中英

CSS opacity transition won't work for Safari

I'm trying to implement some kind of lazy background image loading. I want the image to fade in as soon as it's loaded. Therefore I change the holding div's opacity on load. It work's for Chrome or Firefox, but somehow not for Safari. Using Safari the images just appear without any transition. How so?

import React, {Component} from 'react';

import './ImageHolder.css'

class LazyImage extends Component {

    state = {
        src: null,
    };

    componentDidUpdate(prevProps, prevState, snapshot) {

        if (prevProps.image !== this.props.image) {
            this.setState({src: null});
            this.loadImage();
        }
    }

    componentDidMount() {
        this.loadImage();
    }

    loadImage = () => {
        const src = this.props.image;

        const imageLoader = new Image();
        imageLoader.src = src;

        imageLoader.onload = () => {
            this.setState({src: src})
        };
    };

    classList = (classes) => {
        return Object
            .entries(classes)
            .filter(entry => entry[1])
            .map(entry => entry[0])
            .join(' ');
    };

    render() {
        const style = {
            backgroundImage: 'url(' + this.state.src + ')',
        };

        return(
            <div className="h-image-wrapper" style={{backgroundColor: this.props.bgColor}}>
                <div className={this.classList({
                    'h-image-holder': true,
                    'h-image-loaded': this.state.src,
                })} style={style} />
            </div>
        );
    }
}

export default LazyImage;
.h-image-holder {
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    will-change: opacity, transform;
    pointer-events: none;
    opacity: 0;
    width: 100%;
    height: 100%;
    transition: opacity .6s ease;
    -webkit-transition: opacity .6s ease;
}

.h-image-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    will-change: transform;
    pointer-events: none;
}

.h-image-loaded {
    opacity: 1;
}

Maybe this could help. On the Safari CSS Visual Effects Guide it's says that you have to use this:

-webkit-transition-property: opacity;

You can also change the duration of it doing:

-webkit-transition-duration: 2s;"

it is noted here

Note: Not all CSS properties are animatable. In general, any CSS property that accepts values that are numbers, lengths, percentages, or colors is animatable. Some CSS properties that accept discrete values can be animated as well, but display a jump between values rather than a smooth transition when changed, such as the visibility property.

Safari CSS Reference

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