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>

効果

ここに画像の説明を挿入

エピローグ

終わりました。実装する際には、グローバル カスタム命令を使用して、エラー画像やプロンプト情報の表示を実現することもできます。

おすすめ

転載: blog.csdn.net/qq_43231248/article/details/129404276
おすすめ