Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
975 views
in Technique[技术] by (71.8m points)

javascript - jQuery change div background-image with fadeIn/Out

I'm trying to create a fadeIn/Out effect on a site I created (edit: site url deleted)

Everything works great except when you click on one of the colors in the color palette, it replaces the image with no effect.

This is the small script I wrote, which is triggered onclick on one of the colors.

function changeImage(newColor) {

    //var previousImage = $('#image-holder').css("background-image");

    $('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')");
};

I tried playing with $('#image-holder').fadeOut(1500) and then $('#image-holder').fadeIn(1500) but it acts funny... it double fades the image.

$('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')").fadeOut(function(){$(this).fadeIn()});

What I would like to achieve is onclick on a color box, the current background image will fadeout while the new background image will fade in.

I know it's easier to achieve that if I'd used two <img src="" /> and switch their display/visibility but I unfortunately I can't alter the HTML that much so I'm looking for a jQuery based solution.

Appreciate the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This was the only reasonable thing I found to fade a background image.

<div id="foo">
  <!-- some content here -->
</div>

Your CSS; now enhanced with CSS3 transition.

#foo {
  background-image: url('a.jpg');
  transition: background 1s linear;
}

Now swap out the background

$("#foo").css("background-image", "url(b.jpg)");

Or do it with native javascript

document.querySelector("#foo").style.backgroundImage = "url(b.jpg)";

Voilà, it fades!


Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...