HTML/img:修订间差异
来自康健生活
< HTML
| 第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 */ | |||
<img src="abc.jpg" onerror="javascript:this.src='123.jpg';this.onerror=null" /> | |||
</syntaxhighlight> | |||
2022年8月14日 (日) 14:56的版本
引言
默认图
资源加载失败时,加载默认图。
<img src="abc.jpg" onerror="onerror=null;src='123.jpg'" />
/* or */
<img src="abc.jpg" onerror="javascript:this.src='123.jpg';this.onerror=null" />
react 示例
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}
/>
}
No categories