![](/img/trans.png)
[英]HTML: trigger onerror twice to display the alternate of the alternate image
[英]Display alternate image
如果找不到原始源文件,是否可以顯示備用圖像? 我只想用 css 和 html 來實現這一點,而不是 javascript(或 jQuery 等)。 這個想法是仍然顯示圖像而不是 IE 的“alt”測試或默認(丑陋)交叉。 如果沒有 javascript 是不可能的,那么我寧願使用基本的 if-then-else 檢查帶有 php 的 img src。
用很少的代碼實現這一目標的非常簡單和最好的方法
<img class="avatar" src="img/one.jpg" alt="Not Found" onerror=this.src="img/undefined.jpg">
對我來說,上述工作完美!
你可以使用 img 元素的 CSS background-image 屬性來做到這一點,即
img
{
background-image:url('default.png');
}
但是,您必須為此提供寬度或高度(當找不到 img-src 時):
img
{
background-image:url('default.png');
width:400px;
}
<object data="foobar.png" width=200 height=200>
<img src="test.png" alt="Just testing.">
</object>
這里foobar.png
是主圖像, test.png
是后備圖像。 根據object
元素的語義,當且僅當無法使用主要數據(由data
屬性指定)時,才應呈現元素的內容(此處為img
元素)。
盡管瀏覽器在過去一年中在object
實現中出現了可怕的錯誤,但這種簡單的技術似乎適用於現代版本的 IE、Firefox、Chrome。
是的,您可以僅使用 html 來完成,當找不到 img src 時,它會拋出錯誤,因此我們可以在這里處理它。 還有一點是設置 this.onerror = null 用於遞歸調用(默認圖片未找到)
<img alt="User Image" class="user-image" src="/Resources/images/user-icon.png" onerror="this.onerror=null; this.src='/Resources/images/user-icon.png'">
我在 inte.net 中搜索了解決方案。 但是我在 stackoverflow 中找到的每個解決方案對我來說都失敗了。 我在我的 React 項目中使用了 MUI 組件庫。
我的解決方案:
import React, { FC } from 'react';
import { Avatar } from '@mui/material';
import { IgUser } from '../../utils/__generated__/graphql';
import UserPng from '../../assets/user.png';
interface Props {
talent: IgUser;
}
export const TalentAvatar: FC<Props> = ({ talent }) => {
return (
<Avatar alt={`${talent?.username}`}
src={`${talent?.profile_pic_url}`}>
<Avatar alt="" src={UserPng} />
</Avatar>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.