如何在 javascript 中添加具有多个源标记的图片元素

How to add a picture element in javascript with multiple source tags

我正在尝试这样做

<picture>
  <source srcset="img/awesomeWebPImage.webp" type="image/webp">
  <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> 
  <img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>

但在 javascript 中是这样的

  const image = document.createElement('picture');
  image.className = 'object-img';
  image.src = DBHelper.imageUrlForObject(object);
  image.setAttribute("srcset",`${image.src}_small_1x.jpg 550w, ${image.src}_medium_1x.jpg 800w,
  ${image.src}_large_1x.jpg 1600w`);
  image.setAttribute("srcset",`${image.src}_small_1x.webp 550w, ${image.src}_medium_1x.webp 800w,
  ${image.src}_large_1x.webp 1600w"`);
  image.setAttribute("alt",`Image of ${object.name}`);
  image.alt = `Image of ${object.name}`;
  li.append(image);

这不起作用,我在想,因为我需要以某种方式在其中添加一个 img 标签?

var pcr = document.createElement("PICTURE");
var sc1 = document.createElement("SOURCE");
var sc2 = document.createElement("SOURCE");
var img = document.createElement("IMG");

pcr.srcset="img/awesomeWebPImage.webp";
pcr.type="image/webp";
sc1.srcset="img/creakyOldJPEG.jpg";
sc1.type="image/jpeg";
sc2.srcset="img/creakyOldJPEG.jpg";
sc2.type="image/jpeg";
img.src="img/creakyOldJPEG.jpg";
img.alt="Alt Text!";

pcr.appendChild(sc1);
pcr.appendChild(sc2);
pcr.appendChild(img);
var pcr = document.createElement("PICTURE");
var sc1 = document.createElement("SOURCE");
var sc2 = document.createElement("SOURCE");
var img = document.createElement("IMG");

pcr.srcset="img/awesomeWebPImage.webp";
pcr.type="image/webp";
sc1.srcset="img/creakyOldJPEG.jpg";
sc1.type="image/jpeg";
sc2.srcset="img/creakyOldJPEG.jpg";
sc2.type="image/jpeg";
img.alt="Alt Text!";

pcr.appendChild(sc1);
pcr.appendChild(sc2);
pcr.appendChild(img);

不设置img标签的src。如果你将设置 src 它将立即加载图像。所以你会加载webp和jpg。

后备将根据源类型工作。