HTML/img:修订间差异
来自康健生活
创建页面,内容为“== 引言 == == 默认图 == 资源加载失败时,加载默认图。 <syntaxhighlight lang="html5"> <img src="abc.jpg" onerror="onerror=null;src='123.jpg'" /></s…” |
|||
| (未显示同一用户的2个中间版本) | |||
| 第4行: | 第4行: | ||
<syntaxhighlight lang="html5"> | <syntaxhighlight lang="html5"> | ||
<img src="abc.jpg" onerror="onerror=null;src='123.jpg'" /></syntaxhighlight> | <img src="abc.jpg" onerror="onerror=null;src='123.jpg'" /> | ||
<!-- or this.onerror=null 防止死循环 --> | |||
<img src="abc.jpg" onerror="javascript:this.src='123.jpg';this.onerror=null" /> | |||
</syntaxhighlight> | |||
=== react 示例 === | |||
<syntaxhighlight lang="javascript"> | |||
import React, { useState, useRef, useEffect } from 'react' | |||
export default function(props) { | |||
const imgRef = useRef(null) | |||
const polyfill = () => { | |||
if (imgRef.current && /webp$/i.test(props.src)) { | |||
window.polyfillWebp?.(imgRef.current) | |||
} | |||
} | |||
useEffect(polyfill, [props.src]); | |||
const [imgSrc, setImgSrc] = useState(props.src) | |||
// 加载中 | |||
const handleImageLoaded = ()=>{ | |||
} | |||
// 加载静态资源失败时调用 | |||
const handleImageErrored = ()=>{ | |||
// 查询数据库项目是否有封面图 | |||
// 如果数据库中的项目中存在封面图,只是资源加载失败,则设置 | |||
// setImgSrc('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=') | |||
// 如果数据库中的项目中存在封面图,但是内容存储里面封面图已经被删除 | |||
// 如果项目 | |||
} | |||
return <img | |||
{...props} | |||
ref={imgRef} | |||
src={imgSrc} | |||
onLoad={handleImageLoaded} | |||
onError={handleImageErrored} | |||
/> | |||
} | |||
</syntaxhighlight> | |||