且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery延迟,直到背景图像加载,然后淡入?

更新时间:2023-10-30 11:37:22

这似乎是一个老线程,这个。
希望它可以帮助:

  $(window).load(function(){
$ '')。attr('src','images / imgsrc.png')。load(function(){
$('#loading')。fadeOut(500);
$('#wrapper')。fadeIn(200);
});
});


I've been doing alot of research and there are loads of plugins and tutorials out there that cover the use of large background images. Unfortunately, they all have one thing in common - they use absolutely positioned images to behave as "fake" background images.

Normally that would work fine for me and I've done that before, however, this project has a repeating background image, so it's necessary that I use normal CSS rules to declare the background image.

All of that being said, is there a way to check to see if the image is loaded and tell jQuery to fade this background image in once it is loaded? The main thing I'm looking for is a way for jQuery to verify that the image is actually loaded. If not, then I suppose I need to settle for a simple static delay (which unfortunately ruins the effect for users who have slow connections).

Last thing - can this be done via CSS class switching/toggling so that I can change the body class before and after the image is loaded? This would be a fallback for users without javascript and would make it so I don't have to .hide() my entire body while the background image loads.

*EDIT: This thread seems to have a similar discussion but I don't think it's quite the same thing: How do I delay html text from appearing until background image sprite is loaded? *

* EDIT 2 *

Looks like the above thread worked after all, except I'm still missing the fadeIn effect. I set the fadeIn intentionally high and it's not animating for some reason, any ideas why?

<script>

$(function() {
      // create a dummy image
    var img = new Image();

      // give it a single load handler
    $(img).one('load',function() {
        $('html').css('background','url(<?php bloginfo( 'template_url' ); ?>/images/red_curtain.jpg) top center repeat-y').fadeIn(12000); // fade in the elements when the image loads
    });

      // declare background image source
    img.src = "<?php bloginfo( 'template_url' ); ?>/images/red_curtain.jpg";

      // make sure if fires in case it was cached
    if( img.complete )
        $(img).load();
});

</script>

This seems an old thread but I found a solution for this. Hope it can help:

$(window).load(function(){
    $('<img/>').attr('src', 'images/imgsrc.png').load(function() {
        $('#loading').fadeOut(500);     
    $('#wrapper').fadeIn(200);
});
});