问题
Is it possible to get srcset
to recalculate the browser window size once the page has loaded, and thus update the image its using.
The reason you'd want to do this is because if on a desktop you have your browser window compressed, load a site, then make the browser window bigger, it will just scale the "small.jpg" (as set in the srcset
) so the user will end up with a pixilated image.
I started make a jsfiddle to show the issue, but it dosnt work well, as i think srcset
is calculated by the browser window, rather than the jsfiddle results grid.
If you are interested you can copy and paste below this into a blank html
file and run it in a localserver (must be on a local http:// server so you can view the network debugging tab to see which image the browser has loaded). Running it in the browser via the file url using file:///
wont allow you to see which image is loaded via the network debugging tab.
<body>
<div class="wrapper">
<img
src="http://i.imgur.com/DoWeH0X.jpg?1"
srcset="http://i.imgur.com/QV9vace.jpg?1 1400w, http://i.imgur.com/ZqkR6Bk.jpg?1 800w, http://i.imgur.com/gltBZ06.jpg?1 300w"
alt="#"
>
</body>
</html>
回答1:
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.
回答2:
i found this to force a re-render
var img = document.getElementById('my-element');
img.srcset = img.srcset;
来源:https://stackoverflow.com/questions/30899271/is-it-possible-to-recalculate-the-srcset-image-used-if-browser-window-is-resiz