在一个图片元素中,例如:
<picture class="l-display-block"> <source srcset="https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?downsize=1440px:*, https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?download=2880px:* 2x" media="(min-width: 1025px)"> <source srcset="https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?downsize=1024px:*, https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?downsize=2048px:* 2x" media="(min-width: 769px)"> <source srcset="https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?downsize=768px:*, https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?downsize=1536px:* 2x" media="(min-width: 600px)"> <source srcset="https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?interpolation=progressive-bilinear&downsize=599px:*, https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?downsize=1198px:* 2x"> <img src="https://cache.marriott.com/marriottassets/marriott/NYCXR/nycxr-bar-8322-hor-feat.jpg?downsize=1024px:*" alt="King Cole Bar" class="l-display-block" itemprop="url"> </picture>
如何获取JavaScript中图片元素尺寸最大的图片的网址
我尝试过:
var divs = document.querySelectorAll("source");
for (m = 0; m < divs.length; m++) {
url = img.getAttribute("data-srcset-large")||img.getAttribute("data-srcset")||img.getAttribute("srcset");
if (url!=null) url= url.replace(/\s+[0-9]+(\.[0-9]+)?[wx]/g, "").split(/,/)[0];
}
但它仅获得第一个链接,而没有获得最大尺寸的图像
答案 0 :(得分:1)
我写了这个函数来做这项工作。
function get_filesize(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, false); // Notice "HEAD" instead of "GET",
// to get only the header
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(xhr.getResponseHeader("Content-Length")));
}
};
xhr.send();
}
function LargestDimURLF(img){
var Objs = [];
var sourceElms = img.getElementsByTagName("SOURCE");
for(k=0;k<sourceElms.length;k++){
var sourceElm = sourceElms[k];
var urls = sourceElm.getAttribute("srcset");
if (urls==null) {
for(s=0;s<sourceElm.attributes.length;s++){
var att = sourceElm.attributes[s];
if (att.nodeName.indexOf("data-srcset")!=-1){
urls = att.value;
}
}
}
if (urls!=null) {
urls= urls.replace(/\s+[0-9]+(\.[0-9]+)?[wx]/g, "").split(/,/);
for(j=0;j<urls.length;j++){
var url = urls[j];
get_filesize(url, function(imgSize) {
var Obj={"url":url,"size":imgSize}
Objs.push(Obj);
});
}
}
}
Objs.sort(function(a, b) {
return b.size - a.size;
});
return Objs[0].url||"";
}
var url = LargestDimURLF(document.getElementByID("myPicture"));