Programming

CSS / HTML 만 사용하여 깨진 아이콘을 숨기는 방법은 무엇입니까?

procodes 2020. 6. 1. 20:57
반응형

CSS / HTML 만 사용하여 깨진 아이콘을 숨기는 방법은 무엇입니까?


깨진 이미지 아이콘을 숨기려면 어떻게해야합니까? :예

src 오류가있는 이미지가 있습니다.

<img src="Error.src"/>

솔루션은 모든 브라우저에서 작동해야합니다.


CSS / HTML이 이미지의 링크가 끊어 졌는지 알 수있는 방법이 없으므로 무엇이든 JavaScript를 사용해야합니다.

그러나 이미지를 숨기거나 소스를 백업으로 바꾸는 최소한의 방법이 있습니다.

<img src="Error.src" onerror="this.style.display='none'"/>

또는

<img src="Error.src" onerror="this.src='fallback-img.jpg'"/>

최신 정보

다음과 같은 방법으로이 논리를 여러 이미지에 한 번에 적용 할 수 있습니다.

document.addEventListener("DOMContentLoaded", function(event) {
   document.querySelectorAll('img').forEach(function(img){
  	img.onerror = function(){this.style.display='none';};
   })
});
<img src="error.src">
<img src="error.src">
<img src="error.src">
<img src="error.src">

업데이트 2

A에 대한 CSS 옵션 참조 michalzuber의 대답은 아래를. 전체 이미지를 숨길 수는 없지만 깨진 아이콘의 모양은 변경됩니다.


사람들이 여기에 말한 내용에도 불구하고 JavaScript가 전혀 필요하지 않으며 CSS가 필요하지 않습니다!

실제로 HTML로만 수행 할 수 있고 단순합니다. 이미지가로드되지 않으면 기본 이미지를 표시 할 수도 있습니다 . 방법은 다음과 같습니다.

이것은 IE8까지도 모든 브라우저에서 작동합니다 (2015 년 9 월에 호스팅 한 사이트를 방문한 250,000 명 이상의 방문자 중 ZERO 사람들은 IE8보다 나쁜 것을 사용했습니다.이 솔루션은 문자 그대로 모든 것에 적용됩니다 ).

1 단계 : 이미지를 img 대신 객체 로 참조하십시오 . 객체가 실패하면 깨진 아이콘이 표시되지 않습니다. 그들은 아무것도하지 않습니다. IE8부터는 Object와 Img 태그를 서로 바꿔 사용할 수 있습니다. 당신은 당신이 정기적으로 이미지로 할 수있는 모든 영광스러운 것들의 크기를 조정하고 할 수 있습니다. 객체 태그를 두려워하지 마십시오. 그것은 단지 태그 일뿐 아니라 크고 부피가 큰 것은로드되지 않으며 아무것도 느려지지 않습니다. 다른 이름으로 img 태그를 사용하면됩니다. 속도 테스트는 동일하게 사용되었음을 보여줍니다.

2 단계 : (선택적이지만 굉장합니다) 해당 객체 안에 기본 이미지를 붙여 넣습니다. 원하는 이미지가 실제로 객체에 로드 되면 기본 이미지가 표시되지 않습니다. 예를 들어 사용자 아바타 목록을 표시 할 수 있으며, 누군가 서버에 이미지가없는 경우 자리 표시 자 이미지를 표시 할 수 있습니다. 자바 스크립트 나 CSS가 전혀 필요하지 않지만 대부분의 사람들이 JavaScript를 사용합니다.

코드는 다음과 같습니다.

<object data="avatar.jpg" type="image/jpg">
    <img src="default.jpg" />
</object>

... 예, 그렇게 간단합니다.

CSS로 기본 이미지를 구현하려면 다음과 같이 HTML에서 훨씬 간단하게 만들 수 있습니다.

<object class="avatar" data="user21.jpg" type="image/jpg"></object>

... 그리고이 답변에서 CSS를 추가하십시오-> https://stackoverflow.com/a/32928240/3196360


https://bitsofco.de/styling-broken-images/ 에서 훌륭한 솔루션을 찾았습니다.

img {  
  position: relative;
}

/* style this to fit your needs */
/* and remove [alt] to apply to all images*/
img[alt]:after {  
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  font-family: 'Helvetica';
  font-weight: 300;
  line-height: 2;  
  text-align: center;
  content: attr(alt);
}
<img src="error">
<br>
<img src="broken" alt="A broken image">
<br>
<img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png" alt="A bird" style="width: 120px">


가장 쉬운 방법은 텍스트 들여 쓰기 속성으로 깨진 이미지 아이콘을 숨기는 것입니다.

img {
    text-indent: -10000px
}

"alt"속성을 보려면 분명히 작동하지 않습니다.


자리 표시 자로 이미지를 유지 / 필요한 경우 오류가 발생하고 일부 CSS를 사용하여 불투명도를 0으로 변경하여 이미지 크기를 설정할 수 있습니다. 이렇게하면 끊어진 링크는 보이지 않지만 페이지는 정상적으로로드됩니다.

<img src="<your-image-link->" onerror="this.style.opacity='0'" />

.img {
    width: 75px;
    height: 100px;
}

Nick답변마음 들었고이 솔루션으로 놀고있었습니다. 더 깨끗한 방법을 찾았습니다. :: before / :: after 의사는 img 및 object와 같은 교체 된 요소에서 작동하지 않으므로 객체 데이터 (src)가로드되지 않은 경우에만 작동합니다. HTML을 더 깨끗하게 유지하고 객체가로드되지 않으면 의사를 추가합니다.

http://codepen.io/anon/pen/xwqJKQ

<object data="http://lorempixel.com/200/200/people/1" type="image/png"></object>

<object data="http://broken.img/url" type="image/png"></object>

object {
  position: relative;
  float: left;
  display: block;
  width: 200px;
  height: 200px;
  margin-right: 20px;
  border: 1px solid black;
}
object::after {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: 100%;
  content: '';
  background: red url("http://placehold.it/200x200");
}

If you will add alt with text alt="abc" it will show the show corrupt thumbnail, and alt message abc

<img src="pic_trulli.jpg" alt="abc"/>

1 일

If you will not add alt it will show the show corrupt thumbnail

<img src="pic_trulli.jpg"/>

2 위

If you want to hide the broken one just add alt="" it will not show corrupt thumbnail and any alt message(without using js)

<img src="pic_trulli.jpg" alt=""/>

If you want to hide the broken one just add alt="" & onerror="this.style.display='none'" it will not show corrupt thumbnail and any alt message(with js)

<img src="pic_trulli.jpg" alt="abc" onerror="this.style.display='none'"/>

4th one is a little dangerous(not exactly) , if you want to add any image in onerror event, it will not display even if Image exist as style.display is like adding. So, use it when you don't require any alternative image to display.

display: 'none'; // in css

If we give it in CSS, then the item will not display(like image, iframe, div like that).

If you want to display image & you want to display totally blank space if error, then you can use, but also be careful this will not take any space. So, you need to keep it in a div may be

Link https://jsfiddle.net/02d9yshw/


Using CSS only is tough, but you could use CSS's background-image instead of <img> tags...

Something like this:

HTML

<div id="image"></div>

CSS

#image {
    background-image: url(Error.src);
    width: //width of image;
    height: //height of image;

}

Here is a working fiddle.

Note: I added the border in the CSS on the fiddle just to demonstrate where the image would be.


If you need to still have the image container visible due to it being filled in later on and don't want to bother with showing and hiding it you can stick a 1x1 transparent image inside of the src:

<img id="active-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"/>

I used this for this exact purpose. I had an image container that was going to have an image loaded into it via Ajax. Because the image was large and took a bit to load, it required setting a background-image in CSS of a Gif loading bar.

However, because the src of the was empty, the broken image icon still appeared in browsers that use it.

Setting the transparent 1x1 Gif fixes this problem simply and effectively with no code additions through CSS or JavaScript.


Use the object tag. Add alternative text between the tags like this:

<object data="img/failedToLoad.png" type="image/png">Alternative Text</object>

http://www.w3schools.com/tags/tag_object.asp


You can follow this path as a css solution

img {
        width:200px;
        height:200px;
        position:relative
   }
img:after {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: inherit;
        height: inherit;
        background: #ebebeb url('http://via.placeholder.com/300?text=PlaceHolder') no-repeat center;
        color: transparent;
    }
<img src="gdfgd.jpg">


Since 2005, Mozilla browsers such as Firefox have supported the non-standard :-moz-broken CSS pseudo-class that can accomplish exactly this request:

td {
  min-width:64px; /* for display purposes so you can see the empty cell */
}

img[alt]:-moz-broken {
  display:none;
}
<table border="1"><tr><td>
  <img src="error">
</td><td>
  <img src="broken" alt="A broken image">
</td><td>
  <img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png"
       alt="A bird" style="width: 120px">
</td></tr></table>

img[alt]::before also works in Firefox 64 (though once upon a time it was img[alt]::after so this is not reliable). I can't get either of those to work in Chrome 71.


Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

    //Replace source
    $('img').error(function(){
            $(this).attr('src', 'missing.png');
    });

   //Or, hide them
   $("img").error(function(){
           $(this).hide();
   });

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.


The trick with img::after is a good stuff, but has at least 2 downsides:

  1. not supported by all browsers (e.g. doesn't work on Edge https://codepen.io/dsheiko/pen/VgYErm)
  2. you cannot simply hide the image, you cover it - so not that helpful when you what to show a default image in the case

I do not know an universal solution without JavaScript, but for Firefox only there is a nice one:

img:-moz-broken{
  opacity: 0;
}

For future googlers, in 2016 there is a browser safe pure CSS way of hiding empty images using the attribute selector:

img[src="Error.src"] {
    display: none;
}

Edit: I'm back - for future googlers, in 2019 there is a way to style the actual alt text and alt text image in the Shadow Dom, but it only works in developer tools. So you can't use it. Sorry. It would be so nice.

#alttext-container {
    opacity: 0;
}
#alttext-image {
    opacity: 0;
}
#alttext {
    opacity: 0;
}

코드 없이이 작업을 수행하는 기본적이고 매우 간단한 방법은 빈 alt 문을 제공하는 것입니다. 그런 다음 브라우저는 이미지를 공백으로 반환합니다. 이미지가없는 것처럼 보입니다.

예:

<img class="img_gal" alt="" src="awesome.jpg">

그것을보고보십시오! ;)

참고 URL : https://stackoverflow.com/questions/22051573/how-to-hide-image-broken-icon-using-only-css-html

반응형