Home > Article > Web Front-end > Can\'t Fade Background Image in jQuery? Unlock the Solution
Can't Fade Background Image in jQuery? Try This
While attempting to fade a background image using jQuery, several approaches have proved unsuccessful, including:
var x = 0; while (true) { /* change background-image of #slide using some variation of animate or fadeIn/fadeOut with or without setTimeout */ x++; }
Solution:
The key to this issue lies in the fact that jQuery cannot directly fade background images. To work around this, use tags to represent your images and initially hide them using display: none;. Set their position to absolute and z-index to -1 to mimic background behavior, forcing them to appear behind all other elements.
Here's an example of how to achieve this effect:
HTML:
<img src=".." /> <img src=".." />
CSS:
img{ position:absolute; z-index:-1; display:none; }
jQuery:
function test() { $("img").each(function(index) { $(this).hide(); $(this).delay(3000 * index).fadeIn(3000).fadeOut(); }); } test();
A live demonstration is available at http://jsfiddle.net/RyGKV/.
The above is the detailed content of Can\'t Fade Background Image in jQuery? Unlock the Solution. For more information, please follow other related articles on the PHP Chinese website!