简体   繁体   中英

How to change background-image opacity after .animate() in jquery?

I am working with jQuery animate( function and it contains the following.

$(document).ready(function(){ 
    setInterval(function(){ 
        $("#animate1").fadeIn('slow').animate({
            'margin-left': '150px',
            'margin-bottom': '50px'
        }, 2000).fadeOut();

        $("#animate1").fadeIn('slow').animate({
            'margin-bottom': '0px',
            'margin-left': '-140px'
        }, 2000).fadeOut();
    }, 300);
});
<div style="background-image:url('img/sofa.jpg');">
    <div id="animate1">
        <img src="img/chotu.png" style="height:200px; width:200px;"/>
    </div>
</div>

I want to change my background-image opacity as follows:

$("#animate1").fadeIn('slow').animate({
    'margin-left': '150px',
    'margin-bottom': '50px'
}, 2000)./* change bg-opacity here */.fadeOut();

Is it possible? I simply want to change my background image opacity after my first animate function.

<body>
    <div id="bg"></div>
    ...
</body>

You can make it as wide as the page using CSS:

#bg {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

And then animate it's properties.

$('#bg')
    .animate({opacity: 0}, 'slow', function() {
        $(this)
            .css({'background-image': 'url(1.jpg)'})
            .animate({opacity: 1});
    });

You can get a similar effect by fading the image opacity to 0, then change the background image, and finally fading the image back in again.

You could get more of a crossover effect, by having a second background div on top of this one, which you can then fade in.

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