检查图元素的loaderror背景图象

时间:2014-12-06 09:03:23

标签: jquery

需要使用下面的功能检查此背景图像(图像是否能够加载)。该功能不检查或获取要报告的ID。此外,我希望能够通过Ajax加载(loadmore)的图形项目的功能。

<figure id="2756" class="postitem state-rest" style="background-image: url(http://www.loepfe-co.ch/Wetterdaten/TraisFluors/Bilder/bild.jpg);"></figure>

  function fitcam()
{
$("figure").css('background-image').on({
    load: function() {
        var source = $(this).css('background-image'); 

    },
    error: function() {
        pos3 = $(this).attr("id");
        reportcam();
        $(this).parent().remove();
    }
}); 
 }; 

1 个答案:

答案 0 :(得分:2)

CSS资源没有JavaScript回调,因此您无法直接使用背景图片。相反,你可以做这样的事情(像waitForImages这样的各种jQuery插件):

// method to test if a background file is loadable
function bgLoaded( jqSelector, jqContext  ) {
    // default settings - change them for your needs
    var jqSelector = jqSelector || 'figure',
        jqContext = jqContext || false;
    $(jqSelector,jqContext).each(function() {
      var $figure = $(this), bgImg, bgImgUrl = $figure.css('background-image');
      // check if we have a background image, and the element hasn't been tested before
      if(bgImgUrl && !$figure.hasClass('bg-loaded')) {
        // use the css rule to extract image src
        bgImg = bgImgUrl.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
        // create a temp image element and run the tests
        $('<img/>').attr('src', bgImg).on({
          // in case of success remove temp object to avoid memory leaks
          load : function() {
            $(this).remove();
            // add a class to indicate that this element has been tested
            // you might also use a data-attribute for this
            $figure.addClass('bg-loaded');
          },
          // in case of error remove temp - and whatever your needs are
          error : function() {
            $(this).remove();
            // do what you want here 

            // I would prefer a display instead of removing, because removing
            // could cause flickering effects of the page.                 
            $figure.remove();}
        });
      }
  }); 
}

$().ready(function() {
    // use on load
    bgLoaded();

    // in case you load figures async you call 
    // the method in the success method of your request.
    // bgLoaded accepts a custom selector and a context 
    // so you could enclose the scanning to the ajax response.

});  

您将在此处找到fiddle - 修改图片的网址以测试错误情况。