如果浏览器窗口调整大小,是否可以重新计算使用的`srcset`图像? [英] Is it possible to recalculate the `srcset` image used if browser window is resized?

查看:219
本文介绍了如果浏览器窗口调整大小,是否可以重新计算使用的`srcset`图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过 srcset 在页面加载后重新计算浏览器窗口大小,从而更新其使用的图像。

Is it possible to get srcset to recalculate the browser window size once the page has loaded, and thus update the image its using.

您希望这样做的原因是,如果在桌面上压缩浏览器窗口,加载网站,然后使浏览器窗口变大,只是缩放small.jpg(如 srcset 中设置),因此用户最终会得到一个像素化的图像。

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.

我开始使用jsfiddle显示问题,但它dosnt工作得很好,因为我认为 srcset 通过浏览器窗口,而不是jsfiddle结果网格。

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.

如果您有兴趣,可以将下面的内容复制并粘贴到空白的 html 文件中,然后在本地服务器(必须在本地http://服务器上,因此您可以查看网络调试选项卡,以查看浏览器加载了哪个映像)。使用 file:/// 通过文件url在浏览器中运行它不允许通过网络调试选项卡查看加载了哪个映像。

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>


推荐答案

您可以使用

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

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

这将导致HTML通过解析器再次发送,以根据srcset重新加载图像。

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();
}

这也会导致解析重新呈现html,更多资源。

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

这篇关于如果浏览器窗口调整大小,是否可以重新计算使用的`srcset`图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆