Inputting a default image in case the src attribute of an html

后端 未结 22 2086
渐次进展
渐次进展 2020-11-22 16:02

Is there any way to render a default image in an HTML tag, in case the src attribute is invalid (using only HTML)? If not, what would

22条回答
  •  清酒与你
    2020-11-22 16:16

    I recently had to build a fall back system which included any number of fallback images. Here's how I did it using a simple JavaScript function.

    HTML

    
    

    JavaScript

    function fallBackImg(elem){
        elem.onerror = null;
        let index = +elem.dataset.fallIndex;
        elem.src = elem.dataset[`fallback${index}`];
        index++;
        elem.dataset.fallbackindex = index;
    }
    

    I feel like it's a pretty lightweight way of handling many fallback images.

提交回复
热议问题