简体   繁体   English

如何使用javascript选择具有srcset属性值的图像元素?

[英]How to select image elements with its srcset attribute value using javascript?

for an example ,例如,

<img class="page-hero__image" style="" srcset="https://www.thecloroxcompany.com/wp-content/uploads/160602_fastenclorox_103813-1400x0-c-default.jpg 1600w,
                            https://www.thecloroxcompany.com/wp-content/uploads/160602_fastenclorox_103813-1200x0-c-default.jpg 1200w,
                            https://www.thecloroxcompany.com/wp-content/uploads/160602_fastenclorox_103813-1024x0-c-default.jpg 1024w,
                            https://www.thecloroxcompany.com/wp-content/uploads/160602_fastenclorox_103813-800x0-c-default.jpg 800w,
                            https://www.thecloroxcompany.com/wp-content/uploads/160602_fastenclorox_103813-400x0-c-default.jpg 400w" sizes="(min-width: 1200px) 1200px, 100vw" src="https://www.thecloroxcompany.com/wp-content/uploads/160602_fastenclorox_103813-1000x0-c-default.jpg" alt="">

I need to select the above img element by the srcset attribute and its value using the document.querySelectorAll('img[srcset='value']') .我需要使用document.querySelectorAll('img[srcset='value']')通过 srcset 属性及其值选择上述 img 元素。 How can I do that?我怎样才能做到这一点?

you need to find the image element first and filter by srcset您需要先找到图像元素并通过 srcset 过滤

var images = document.getElementsByTagName('img'); 
for(var i = 0; i < images.length; i++) {
    if(images[i].src == srcset) //check with your srcset
       console.log("found image element"); //image[i] has found element
} 

or you can use this way too或者你也可以用这种方式

document.querySelectorAll('img[srcset="value"]');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM