css处理图片失效显示错误兜底图代码

简言

今天从张老师那里学到了图片加载错误后显示兜底图和提示文字的用法。用vue实现下图片组件。

代码

思路: 图片加载失败,添加错误css类,添加伪类填充错误图片和alt提示信息

<template>
  <img
    :class="{ is__error: isOnloadError }"
    :src="src"
    :alt="alt"
    class="image"
    @error.once="errorEvent"
  />
</template>
<script lang="ts" setup>
import { ref } from 'vue'

const isOnloadError = ref(false)
const props = defineProps({
  src: {
    //  图片路径
    type: String,
    default: () => ''
  },
  alt: {
    //  文字提示
    type: String,
    default: () => ''
  }
})
//  加载错误事件
const errorEvent = () => {
  isOnloadError.value = true
}
</script>
<style lang="scss" scoped>
.image.is__error {
  position: relative;
  display: inline-block;
  width: 100px;
  height: 100px;
}
.image.is__error::before {
  content: attr(alt);
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: center;
  color: #fff;
  background-color: rgba($color: #000000, $alpha: 0.6);
  z-index: 2;
}
.image.is__error::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('@/assets/images/error/img_error.jpg') center no-repeat;
}
</style>

效果

在这里插入图片描述

结语

结束了。实现时也可以使用全局自定义指令来实现错误图片和提示信息的显示。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZSK6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值