如何使用javascript为我的图像添加属性?

时间:2018-04-20 23:34:36

标签: javascript html html5 image

我想知道如何将图像属性添加到以下代码中。我添加了一个teest函数来查看用户浏览器是否支持webp图像,如果它没有显示jpg图像而不是webp但是我想添加属性而没有任何我做过的工作

function hasWebP() {
  var rv = $.Deferred();
  var img = new Image();
  img.onload = function() { rv.resolve(); };
  img.onerror = function() { rv.reject(); };
  img.src = '/images/home/dot.webp';
  return rv.promise();
}
hasWebP().then(function() {
    var img=document.createElement("img");
    img.src="images/home/IMG_4389.webp";
    img.id="picture";
    var foo = document.getElementById("myFace");
    foo.appendChild(img);
}, function() {
    var img=document.createElement("img");
    img.src="images/home/IMG_4389.png";
    img.id="picture2";
    var foo = document.getElementById("myFace");
    foo.appendChild(img);
});

1 个答案:

答案 0 :(得分:1)

我将代码更改为

function hasWebP() {
  var rv = $.Deferred();
  var img = new Image();
  img.onload = function() { rv.resolve(); };
  img.onerror = function() { rv.reject(); };
  img.src = '/images/home/dot.webp';
  return rv.promise();
}
hasWebP().then(function() {
    document.getElementById("picture").src="/images/home/IMG_4389.webp";
}, function() {
    document.getElementById("picture").src="/images/home/IMG_4389.png";
});

并将此添加到我的HTML

<img src="" id="picture" draggable="false">
相关问题