在 Chrome 中,img 元素的 currentSrc 有时为空。我怎样才能防止这种情况发生?

Sea*_*ean 5 javascript google-chrome drupal-8 picture-element responsive-images

更新:

我刚刚找到了一些更多信息。看来在 Chrome 中,图像的 currentSrc 通常是空的,而在 Firefox 中,URL 总是正确的。JS 是否在 currentSrc 可用之前尝试访问它?有办法防止这种情况吗?


我正在创建一个 Drupal 8 网站,为了将响应式图像模块与背景图像一起使用,我想出了以下解决方法。下面的 JS 函数 setParallaxImage() 从图片元素中的 img 中获取 currentSrc,并将其设置为最外层 div 的背景图像。img 本身不显示(CSS 中的 display: none),并给出一个虚拟图像,因为我只需要它来获取 currentSrc。该函数通过 onload 和 onresize 调用。

该代码似乎在 Firefox 中运行良好。当调整浏览器大小超过断点时,图像会瞬间变成灰色,然后从正确的源加载图像。然而,对于 Chrome,当快速调整大小超过断点时,图像可能会变成灰色并且根本不显示,即,background-image: url()。通常,如果我再调整窗口大小几次,图像最终就会出现。有谁知道为什么会发生这种情况?感谢您的阅读。

JS

function setParallaxImage() {


    const parallaxContainer = document.getElementsByClassName('paragraph--type--parallax-banner-with-text');

    for(var i = 0; i < parallaxContainer.length; i++) {
      console.log('in setparallax');
      var x = parallaxContainer[i];
      var parallax = x.getElementsByClassName('field--name-field-parallax-image-top-')[0];
      var picture = parallax.getElementsByTagName("picture")[0];
      var sourceURL = picture.querySelector('img').currentSrc;
      x.setAttribute('style', 'background-image: url(' + sourceURL +')');
      var img = picture.getElementsByTagName("img")[0].setAttribute('src', '/sites/default/files/src_images/dummy_image.gif');
    }
  }

window.onload = setParallaxImage
window.onresize = setParallaxImage;
Run Code Online (Sandbox Code Playgroud)

超文本标记语言

<div class='paragraph--type--parallax-banner-with-text'>
 <div class='field--name-field-parallax-image-top-'>
  <picture>
   <!-- several source tags here -->
   <img src="will-be-given-dummy-image-in-JS">
  </picture>
 </div>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 2

您可以使用“完整”属性来检查图像是否已加载。如果没有,您可以在图像可用时使用 onload-Event 来触发。

if (img.complete) {
    console.log(img.currentSrc);
} else {
    img.onload = function() {
        console.log(img.currentSrc);
    }
}
Run Code Online (Sandbox Code Playgroud)