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

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些