jQuery/JavaScript to replace broken images

后端 未结 30 3112
我寻月下人不归
我寻月下人不归 2020-11-21 05:50

I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.

How do I use jQuery

30条回答
  •  没有蜡笔的小新
    2020-11-21 06:16

    This has been frustrating me for years. My CSS fix sets a background image on the img. When a dynamic image src doesn't load to the foreground, a placeholder is visible on the img's bg. This works if your images have a default size (e.g. height, min-height, width and/or min-width).

    You'll see the broken image icon but it's an improvement. Tested down to IE9 successfully. iOS Safari and Chrome don't even show a broken icon.

    .dynamicContainer img {
      background: url('/images/placeholder.png');
      background-size: contain;
    }
    

    Add a little animation to give src time to load without a background flicker. Chrome fades in the background smoothly but desktop Safari doesn't.

    .dynamicContainer img {
      background: url('/images/placeholder.png');
      background-size: contain;
      animation: fadein 1s;                     
    }
    
    @keyframes fadein {
      0%   { opacity: 0.0; }
      50%  { opacity: 0.5; }
      100% { opacity: 1.0; }
    }
    

提交回复
热议问题