リンク切れに代替画像を表示

リンク切れ画像の代替画像表示について何個か。リンク切れ画像は非表示にする。

  1. <img src="original.png" alt="title" onerror="this.style.display='none'"/>

代替画像を表示にする。

  1. <img src="original.png" alt="title" onerror="this.src='https://your-site-url-image'"/>

スタイルシートで。これを採用した。

  1. <style>
  2.  <!--
  3. img:before {
  4.   content: " ";
  5.   display: block;
  6.   position: absolute;
  7.   top: -20px;
  8.   margin-left : 0px;
  9.   height: calc(100% + 40px);
  10.   width: 100%;
  11.   background-color: #fff;
  12.   border-radius: 10px;
  13. }
  14. img {
  15.   position: relative;
  16. }
  17. /* Broken link koriki */
  18. img[alt]:after {
  19.   display: block;
  20.   position: absolute;
  21.   width: 85px;
  22.   height: 85px;
  23.   margin-top : -56px;
  24.   margin-left : 46px;
  25.   background: #ebebeb url('https://') no-repeat center;
  26.   background-color: #fff;
  27.   font-family: 'Helvetica';
  28.   font-weight: 300;
  29.   line-height: 2;
  30.   text-align: center;
  31.   content: attr(alt);
  32. }
  33. -->
  34. </style>

JavaScript。

  1. <!-- Broken link koriki -->
  2. document.addEventListener('DOMContentLoaded', () => {
  3. const images = [].slice.call(document.querySelectorAll('img'));
  4. images.forEach((image) => {
  5. image.addEventListener('error',() => {
  6. image.setAttribute('src','https://');
  7.  });

もしリンク切れの場合は代替画像が表示されます。わざとリンク切れさせてみますね。

パーやん

43歳のおじさんがこんなものを夜な夜な作って妻が切れてます。

最終更新日:2020/12/07