【问题标题】:Get the current image source of a picture element获取图片元素的当前图像源
【发布时间】:2017-01-20 11:29:10
【问题描述】:

HTMLImageElement 有一个currentSrc 属性,因此我们可以获得img 元素的当前源。在使用 srcset 定义多个可能的来源时很有用。

HTMLPictureElement 似乎没有等价物。

还有其他方法可以使用 Javascript 找到 picture 元素的当前来源吗?

【问题讨论】:

  • picture 只是一个容器元素,为图片容器内的图像元素提供不同的来源 - 所以我假设img 元素的currentSrc 在这里的工作方式相同......?跨度>
  • @CBroe 说得通,你知道任何解释这个的文档吗?
  • @CBroe 你说得对。谢谢!

标签: javascript responsive-images srcset


【解决方案1】:

您可以在picture 元素中访问img 元素的currentSrc 以获取应用的图像。

在下面的演示中(如果您在桌面上使用全角浏览器)currentSrc 将是 http://placehold.it/600x100 图像。

window.onload = function() {
  const picture = document.getElementById('pictureEl');
  const currentSource = document.getElementById('currentSource');
  currentSource.innerText = picture.querySelector('img').currentSrc;
}
<picture id="pictureEl">
 <source srcset="http://placehold.it/600x100?text=Source" media="(min-width: 300px)">
 <img src="http://placehold.it/300x100?text=Img">
</picture>
<div id="currentSource"></div>

【讨论】:

  • 非常有帮助!
【解决方案2】:

使用它来获取图像的来源。

function getCurrentSrc(element, cb){
    var getSrc;
    if(!window.HTMLPictureElement){
        if(window.respimage){
            respimage({elements: [element]});
        } else if(window.picturefill){
            picturefill({elements: [element]});
        }
        cb(element.src);
        return;
    }

    getSrc = function(){
        element.removeEventListener('load', getSrc);
        element.removeEventListener('error', getSrc);
        cb(element.currentSrc);
    };

    element.addEventListener('load', getSrc);
    element.addEventListener('error', getSrc);
    if(element.complete){
        getSrc();
    }
}

【讨论】:

  • window.respimagewindow.picturefill 来自哪里?
  • 它们不作为本机浏览器方法存在,但有 2 个具有这些名称的库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 2012-05-22
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多