Trigger event on background image load

后端 未结 4 1457
甜味超标
甜味超标 2021-01-11 11:56

Is there a way, using jQuery, to trigger an event on load of a CSS background image?

相关标签:
4条回答
  • 2021-01-11 12:11

    I found that the problem with IE is cache: http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/

    so you could try this:

    $(”).attr({src: src + ‘?random=’ + (new Date()).getTime()}).load(function (){
      //custom code here....
    });
    
    0 讨论(0)
  • 2021-01-11 12:13

    you could do it like this,

    demo

    $('<img>').load(function(){
        // make sure to bind the load event BEFORE setting the "src"
        alert('image loaded');
    }).attr('src',function(){
        var imgUrl = $('body').css('background-image');
        imgUrl = imgUrl .substring(4, imgUrl .length-1);
        return imgUrl;
    }).each(function() {
        // fail-safe for cached images which sometimes don't trigger "load" events
        if(this.complete) $(this).load();
    });
    
    0 讨论(0)
  • 2021-01-11 12:15
    $('<img>').attr('src',function(){
        var imgUrl = $('#body').css('background-image');
        imgUrl = imgUrl .substring(5, imgUrl .length-2);
        return imgUrl;
    }).load(function(){
        //Do Something
    });
    

    Could not help but notice that the above code does not work in fiddle. Looks like its because it returns "url('/img-path.jpg')" instead of just "/img-path.jpg".

    However this method still fails in IE. Anyone have an ie fix?

    0 讨论(0)
  • 2021-01-11 12:16
    $(document).ready(function(){
    $('img, .hasBGI').css('opacity',0)
    
    $('.hasBGI').each(function(){
        var $this = $(this)
            $bgi = $('<img src="'+/*folderFix*/$this.css('backgroundImage')+'">')
            // $bgi.css(/*hiddingStyle*/)
            $('body').append($bgi)
            $bgi.load(function(){
                $(this).remove()
                $this.animate({opacity:1})
            })
    })
    $('img').load(function(){
        $(this).animate({opacity:1})
    })
    

    })

    0 讨论(0)
提交回复
热议问题