自动填充图片网址

时间:2018-11-12 13:35:41

标签: javascript jquery

我正在检查浏览器是否为chrome。如果是chrome,则我只显示具有(data-mobileWebp)或(data-desktopWebp)属性的Webp图像。有时,Webp图像不会在后端上传,所以我需要退回到通常总是像data-mobileImage或data-desktopImage

一样上传的普通图像。

以下代码无法正常工作:

mobileImage = $('.mobileImages', picture).data('mobileWebp') != null ? $('.mobileImages', picture).attr('data-mobileWebp') : $('.mobileImages', picture).attr('data-mobileImage');
desktopImage = $('.desktop-images', picture).data('desktopWebp') != null ? $('.desktop-images', picture).attr('data-desktopWebp') : $('.desktop-images', picture).attr('data-desktopImage');

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

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

    if (is_chrome) {
      mobileImage = $('.mobileImages', picture).data('mobileWebp') != null ? $('.mobileImages', picture).attr('data-mobileWebp') : $('.mobileImages', picture).attr('data-mobileImage');
      desktopImage = $('.desktop-images', picture).data('desktopWebp') != null ? $('.desktop-images', picture).attr('data-desktopWebp') : $('.desktop-images', picture).attr('data-desktopImage');
    } 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);
  });
}
<isif condition="${desktopImage || mobileImage}">
  <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>
</isif>

1 个答案:

答案 0 :(得分:0)

您为什么不使用Modernizr?

Modernizr.on('webp', function (result) {

  console.log(result);  
  if (result) {
    // Has WebP support
  }
  else {
    // No WebP support
  }
});

http://www.stucox.com/blog/using-webp-with-modernizr/