微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – img没有响应srcset指定的维度

我想使用srcset来实现响应图像,如 here所述,所以用户加载的图像src与他的分辨率最相似.

事情是我做了这个测试,它没有响应视口的变化,

<img src="https://lorempixel.com/400/200/sports/"
      alt=""
      sizes="(min-width:1420px) 610px,(min-width:1320px) 500px,(min-width:1000px) 430px,(min-width:620px)  280px,280px"
      srcset="https://lorempixel.com/620/200/sports/ 280w,https://lorempixel.com/1000/300/animals/ 430w,https://lorempixel.com/1320/400/cats/ 610w,https://lorempixel.com/1420/500/abstract/ 1000w,https://lorempixel.com/1600/600/fashion/ 1220w" />

jsfiddlehttp://jsfiddle.net/ad857m1r/9/

任何想法我失踪了?

解决方法

首先加载srcset属性由浏览器解释,然后将加载的映像存储在缓存和 the browser could not load any other image中,直到您清除缓存并重新加载页面.

如果您希望在页面的每个resize事件上重新解释srcset,您需要更新它,但在每个URL的末尾添加一个随机变量,然后浏览器重新加载正确的一个.

I’ve added a delay to this process to reduce the number of times that it is executed. You’ll notice that this practice forces the browser to download the correct image at each resizing and this is bad for bandwidth. I not recommend the use of this technique,let the browser decide which image uses in each situation. I think that the viewport resize is not a common situation in an everyday environment. Maybe is better for your purposes the use of 07001 as @KrisD said.

var img = document.getElementById('myImage');
var srcset = img.getAttribute("srcset");
var delay;

window.onresize = function() {

    if(!isNaN(delay)) clearTimeout(delay);

    delay = setTimeout(refreshImage,500);

}

function refreshImage() {

    var reg = /([^\s]+)\s(.+)/g;
    var random = Math.floor(Math.random() * 999999);

    img.setAttribute("srcset",srcset.replace(reg,"$1?r=" + random + " $2"));

}

jsfiddle

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐