javascript - 在 Javascript 中显示图像的条件

标签 javascript html css image visibility

我正在寻找创建一个小的 javascript 代码来显示图像(如果它们的 src 有效的话)。

为了更好地组织,我必须将脚本分离到 html 页面。

这是我所做的: HTML

<img id="thmb" src= "http://blog.lefigaro.fr/bd/img-sanctuaire.png" width="50px" height="50px" alt="" ;>

JavaScript

var thumbnail = document.images.thmb;

    if(thumbnail.src)
    {
        if(thumbnail.onerror)
        {
            thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
        }
    }
    else
    {
        thumbnail.style.display = "none";
    }

但它不起作用,当我清空 HTML 中的 src 代码时,图像的边框仍在页面中。如果我写错了 URL,我们就看不到 JavaScript 中设置的图像。 这是 JSFiddle 来试验它。 http://jsfiddle.net/gUb8X/

我是 JavaScript 的初学者。 谢谢!

最佳答案

你考试太晚了。

试试这个

Live Demo

window.onload=function() {
  var thumbContainer = document.getElementById("thmbDiv");
  var thumbnail = document.createElement("img");
  thumbnail.onload=function() {
    thumbContainer.appendChild(thumbnail);
  }
  thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}

现在用 id 为 thmbDiv 的 div 替换你的图像

如果您放置占位符或隐藏所有要测试的图像,您可以从数据属性中获取 src。

Live Demo

window.onload=function() {
  var imgs = document.images; // or document.getElementsByClassName("testImage");
  for (var i=0, n=imgs.length;i<n;i++) { 
    var theImage = imgs[i];   
    var src = theImage.getAttribute("data-src");
    if (src) {
      theImage.onerror=function() {
        this.style.display="none"; // or this.parentNode.removeChild(this);
      }
    }
    theImage.src=src;  
  }
}    

关于javascript - 在 Javascript 中显示图像的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19893577/

相关文章:

javascript - 平行线图的制作方法

javascript - Webpack UglifyJS 遇到意外 token

html - 我该如何使用:not to give some specific CSS to parent element not to the child and sub-child?

javascript - jQuery - 数组没有显示正确的值

javascript - 从 Iframe 触发 Jquery 动画

css - 使用 w3 total cache plugin for wordpress 生成的缩小 css 文件时如何处理 css 中的相对字体链接

javascript - 序列化多态 JavaScript 对象

javascript - ID 数组、Restangular、.several()

移动到外部 .js 文件时 JavaScript 不工作

javascript - 外部 JavaScript 函数编辑 HTML 列表标题