Trigger event on background image load

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

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

4条回答
  •  旧时难觅i
    2021-01-11 12:13

    you could do it like this,

    demo

    $('').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();
    });
    

提交回复
热议问题