获取图片元素的当前图像源 [英] Get the current image source of a picture element

查看:59
本文介绍了获取图片元素的当前图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTMLImageElement 具有 currentSrc 属性,这样我们就可以获取 img 元素的当前来源.在使用 srcset 定义多个可能的源时很有用.

An HTMLImageElement has a currentSrc property so we can get the current source of an img element. Useful when defining multiple possible sources with srcset.

HTMLPictureElement 似乎没有等效的功能.

There seems to be no equivalent for an HTMLPictureElement.

还有另一种方法可以使用Javascript查找 picture 元素的当前来源吗?

Is there another way we can find the current source of a picture element with Javascript?

推荐答案

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

You can access the currentSrc of the img element within a picture element to get the applied image.

在下面的演示中(如果您使用的是全屏浏览器,则为 currentSrc )为 http://placehold.it/600x100 图片.

In the demo below (if you're on a desktop with your browser full-width) the currentSrc will be the http://placehold.it/600x100 image.

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>

这篇关于获取图片元素的当前图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆