开发者

How to hide space for image when no images found in the server?

I have data aggregator, organize the data from different source by specific manner.

Sometimes the images given in the source type is not available or the source refused to serve the images. In this case, I want to开发者_如何学Go remove the space given for image tag. Is it possible?

How to hide space for image when no images found in the server?

I want to hide the highlighted area space when no image found or serve refused to serve the image.


The best way to do that would be to use the onerror function. Something like this:

<img src="image_not_found.jpg" onerror="this.style.display = 'none';" alt="">

You can find out more about it here http://msdn.microsoft.com/en-us/library/cc197053(v=vs.85).aspx

edit

Even though this will work for all the browsers, using the onerror attribute will make your HTML invalid since it is not part of the img attribute list. An article on the pros and cons for using this attribute. http://blog.sociomantic.com/2010/07/html-onerror-the-good-the-bad-and-the-ugly/


Simplest solution I can think of: set the server up so that it sends back a 1px * 1px image instead of 404ing.


Alternatively, if you want to do it all client-side (and have image links to other servers that you don't control as well), you can run a javascript function over those images to determine if they're loaded successfully, and if not, set their jsObject.style.display = 'none' for jsObject being each image that didn't load.

Or try this example for replacing images that failed to load with a specified "missing" placeholder image.


If you have no control of the server-side code, you can use JavaScript. Since I don’t see a “broken image” that a browser uses when the src of an image element is broken I’m assuming the container is just empty.

Assuming the container of the image has a class called .container, you can use this snippet of code if you have jQuery:

$(document).ready(function() {

  $('.container').each(function() {
    if ($(this).html() == "") {
      $(this).css('display', 'none');
    }
  });

});

Or better yet, with CSS alone, still assuming the container element has a class name called .container:

.container:empty {
  display: none;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜