next.js 如果图像源中断或丢失,则显示范围

rqenqsqc  于 2023-04-20  发布在  其他
关注(0)|答案(2)|浏览(126)

你好,我正试图在next.js中显示一个徽标,我的想法是如果徽标不可用,则显示一个Span,如果是,则隐藏它。

<div className='brand'>
  <Link href="#">
    <img src="#" alt="UnSet" />
    <span>UnSet</span>
  </Link>
</div>

我尝试了这个,它隐藏了图像,现在我想实现,如果图像是空的,它会显示span内容,如果不是,它会显示图像。

.brand a img[src]{
  display: none;
}

有什么办法吗?

rjzwgtxy

rjzwgtxy1#

您可以使用一些css和一个简单的JavaScript函数来完成此操作。
使用同级选择器设置CSS:

.brand span {
  display: none;
}
.brand img.unset {
  display: none;
}
.brand img.unset + span {
  display: block;
}

然后将其添加到图像对象。

let images = document.querySelectorAll(".brand img");
for (i of images) {
  i.onerror = () => {
    this.classList.Add("unset");
    this.onerror = null;
  }
}
xt0899hw

xt0899hw2#

你应该import Image from 'next/image'
Reference
然后

<div className='brand'>
   <Link href="#">
      <Image src="#" alt="UnSet" unsized />
   </Link>
</div>

相关问题