为单独的图片srcset和img src分配属性

时间:2018-10-31 12:25:43

标签: jquery

当网站上只有1个图片标签时,下面的代码有效。当图片标签在后端添加图片时,会自动动态创建图片标签。因此,我将data属性的值分配给img src,将其他属性分配给源srcset

当有多个图像时,所有图片标签本身都具有第一个图像源。我想要同一个元素的srcset或src而不是其他图片元素的src。 我在敲打头,谢谢您的提前输入。

var is_chrome = (typeof window.chrome === 'object' && navigator.appVersion.indexOf('Edge') === -1);

if ($('.image-browsers').length > 0) {
  if (is_chrome) {
    var mobWebp = $('.mobileImages').attr('data-mobileWebp'),
      deskWebp = $('.desktop-images').attr('data-desktopWebp');
    $('.mobileImages').attr('srcset', mobWebp);
    $('.desktop-images').attr('src', deskWebp);
  } else {
    var mobImage = $('.mobileImages').attr('data-mobileImage'),
      deskImage = $('.desktop-images').attr('data-desktopImage');
    $('.mobileImages').attr('srcset', mobImage);
    $('.desktop-images').attr('src', deskImage);
  }
}
<picture class="image-browsers">
  <isif condition="${mobileImage}">
    <source class="mobileImages" srcset="" media="(max-width: 768px)" data-mobileImage="${mobileImage ? mobileImage.getURL() : ''}" data-mobileWebp="${mobilewebpImage ? mobilewebpImage.getURL() : ''}">
  </isif>
  <isif condition="${desktopImage}">
    <img class="desktop-images" src="" alt="${'previewName' in contentAsset.custom && contentAsset.custom.previewName != null ? contentAsset.custom.previewName : '' }" title="${'previewName' in contentAsset.custom && contentAsset.custom.previewName != null ? contentAsset.custom.previewName : '' }"
      data-desktopImage="${desktopImage ? desktopImage.getURL() : ''}" data-desktopWebp="${desktopwebpImage ? desktopwebpImage.getURL() : ''}">
  </isif>
</picture>

1 个答案:

答案 0 :(得分:1)

您必须为每个.image-browsers元素运行代码

var is_chrome = (typeof window.chrome === 'object' && navigator.appVersion.indexOf('Edge') === -1);
var imageBrowsers = $('.image-browsers');

if (imageBrowsers.length > 0) {
  imageBrowsers.each(function(index, picture) {
    var mobileImage,
      desktopImage;

    if (is_chrome) {
      mobileImage = $('.mobileImages', picture).attr('data-mobileWebp');
      desktopImage = $('.desktop-images', picture).attr('data-desktopWebp')
    } else {
      mobileImage = $('.mobileImages', picture).attr('data-mobileImage');
      desktopImage = $('.desktop-images', picture).attr('data-desktopImage')
    }

    $('.mobileImages', picture).attr('srcset', mobileImage);
    $('.desktop-images', picture).attr('src', desktopImage);
  });
}