簡體   English   中英

如何使用javascript向圖像添加屬性?

[英]How do i add attributes to my images with javascript?

我想知道如何將圖像屬性添加到以下代碼中。 我添加了一個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);
});

我將代碼更改為

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">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM