[英]Load images only for devices with > 640px screen
I have image that should be seen on desktop screens, but not on mobile. 我有应该在台式机屏幕上看到的图像,但不能在移动设备上看到。 I know that CSS media queries are designed only for displaying purposes, which means that on mobile device, image will still be loaded but just not displayed.
我知道CSS媒体查询仅用于显示目的,这意味着在移动设备上,图像仍会加载,但不会显示。 Is there a way to prevent image from loading on devices with <640px resolution?
有没有一种方法可以防止图像在<640px分辨率的设备上加载?
window.onload = function(){
if(document.body.clientWidth> 600){
// . . . code . . .
}
}
You can check the width of the page on load, and based on that set the src
attributes on the images if required. 您可以检查加载页面的宽度,然后根据需要在图像上设置
src
属性。
if(window.innerWidth > 600) { document.getElementById("img1").src = "//placehold.it/150"; } else { alert("No image loaded"); }
<img id="img1" src="" />
Now, a concern might be that this merges the UI logic (ie the URL of the image) into JS. 现在,可能需要担心的是,这会将UI逻辑(即图像的URL)合并到JS中。 You can avoid that by using a data attribute such as
data-src
to keep the actual image src
and set it dynamically to src
based on window.innerWidth
. 您可以通过使用诸如
data-src
类的数据属性来保留实际图像src
并根据window.innerWidth
将其动态设置为src
来避免这种情况。 Something like the following: 类似于以下内容:
if(window.innerWidth > 600) { var img = document.getElementById("img1"); img.src = img.attributes["data-src"].value; } else { alert("No image loaded"); }
<img id="img1" src="" data-src="//placehold.it/150" />
With pure CSS, you can't. 使用纯CSS,您做不到。
You have two options: 您有两种选择:
Option 1: HTML5 选项1:HTML5
If you don't need to support old browsers, you can use HTML5 new tag <picture>
. 如果不需要支持旧的浏览器,则可以使用HTML5新标签
<picture>
。 Like so: 像这样:
<picture>
<source
media="(min-width: 641px)"
srcset="images/my_desktop_image.png">
<source
media="(min-width: 451px)"
srcset="images/my_mobile_image.png">
<img
src="images/my_default_image.png"
alt="picture text">
</picture>
Option 2: Javascript (might be easier with jQuery library) 选项2:JavaScript (使用jQuery库可能会更容易)
With jQuery, you can detect window size, and based on that load the desired image: 使用jQuery,您可以检测窗口大小,并根据该大小加载所需的图像:
$(window).resize(function() {
if($(this).width > 640) {
// load image..
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.