Is it possible to recalculate the `srcset` image used if browser window is resized?

限于喜欢 提交于 2019-12-03 05:46:11

You can use

var img = document.getElementById('resizeMe');

window.onresize = function() {
    img.outerHTML = img.outerHTML;
}

Which will cause the HTML to be sent through the parser again, causing the browser to reload the image according to the srcset.

Of course you should probably include some logic to detect if the screen size has changed to a size outside of the current range so the image isn't reloaded every single time the user resizes the window slightly.


Or, you could clone the node, insert it before the current node, then remove the old node.

var img = document.getElementById('resizeMe');

window.onresize = function() {
    var clone = img.cloneNode(true);
    img.parentNode.insertBefore(clone, img);
    img.remove();
}

Which will also cause the parse to re-render the html, but will consume more resources.

bas

i found this to force a re-render

var img = document.getElementById('my-element');

img.srcset = img.srcset;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!