简体   繁体   中英

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

I am trying to do this

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

but in javascript like this

  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);

This doesn't work, I am thinking because I need to add an img tag in there somehow?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM