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

前端 未结 2 1191
心在旅途
心在旅途 2021-02-07 12:22

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 t

相关标签:
2条回答
  • 2021-02-07 12:51

    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.

    0 讨论(0)
  • 2021-02-07 12:51

    i found this to force a re-render

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

    img.srcset = img.srcset;

    0 讨论(0)
提交回复
热议问题