在jquery中检查图像源是否有图像

时间:2017-05-15 04:27:31

标签: javascript jquery html css laravel-5.4

如果没有图像需要在jquery中隐藏div,我需要在图像源有图像(来自服务器端的图像)时隐藏div

这是我的html文件

<div class="form-group bc-my-group">
     <label>Photo Upload</label>
     <div class="input-group image-preview">
         <input id="imageToUpload" class="form-control image-preview-filename" type="file" accept="image/png, image/jpeg, image/gif" name="images" />
         <div class="help-block with-errors"></div>
     </div>
</div>
<div class="form-group bc-my-group">
     <label>My Photo</label>
     <div id="prof_image">
          <img src ="{{ asset($profile) }}">
     </div>
</div>

有人能给我一个想法吗?

4 个答案:

答案 0 :(得分:3)

  

您可以使用JavaScript中的onerror事件在图像失败时执行操作   加载:

 var img = document.getElementById("myImg");
    img.onerror = function () { 
        this.style.display = "none";
    }
  

在jQuery中(因为你问过):

 $("#myImg").error(function () { 
        $(this).hide(); 
    });
  

或所有图片:

$("img").error(function () { 
    $(this).hide();
    // or $(this).css({visibility:"hidden"}); 
});

如果隐藏图像可能会更改布局,则应使用visibility:hidden而不是.hide()。网络上的许多网站使用默认&#34;无图像&#34;相反,当指定的图像位置不可用时,将src属性指向该图像。

  

您的解决方案只需使用此

 $("#prof_image img").error(function () { 
   $(this).parent().hide(); 
 });

答案 1 :(得分:0)

您可以使用javascript执行此操作:

CSS:

.div {
display: none;
}

JavaScript:

$('.image').onload = function() {
    // image exists and is loaded
    $('.div').show();
}

答案 2 :(得分:0)

如果您指定了想要隐藏的div和图像以及在没有图像时要隐藏哪个div会更容易,我想你想要隐藏带有照片上传的div如果你已经有了图像。

答案 3 :(得分:0)

您可以通过检查源代码在Laravel模板中执行此操作,并添加名为hide的类,

{{ asset($profile)==''?'hide':'' }}

代码,

<div class="form-group bc-my-group {{ asset($profile)==''?'hide':'' }}">
     <label>Photo Upload</label>
     <div class="input-group image-preview">
         <input id="imageToUpload" class="form-control image-preview-filename" type="file" accept="image/png, image/jpeg, image/gif" name="images" />
         <div class="help-block with-errors"></div>
     </div>
</div>

CSS 中,创建一个类,

.hide{display:none !important;}