[英]Img srcset loading images when browser at half image size
( 使用最新版本的Firefox )
我的img
写成这样:
<body>
<script>
function imageLoaded(img) {
console.log('the responsive image is loaded');
img.className += ' loaded';
}
</script>
<img class="backgroundImage"
onload="imageLoaded(this)"
src="assets/water_bg_1920.jpg"
sizes="100vw"
srcset="assets/water_bg_2560.jpg 2560w,
assets/water_bg_1920.jpg 1920w,
assets/water_bg_1024.jpg 1024w"/>
</body>
还有我的css
@keyframes fadeIn
0%
opacity: 0
100%
opacity: 1
.backgroundImage
opacity: 0
.loaded
opacity: 1
animation: fadeIn 3s
当我的浏览器为960px
,它将加载1920
图像。 512px
它将加载1024
图片。 任何更高的值都会加载2560
图像。
当我将sizes
设置为100vw
时, 如何决定以这些宽度加载这些图像,我感到非常困惑。 在浏览器宽度为1024px
之前,它不应该使用1024
图像吗?当浏览器宽度为1024px - 1920px
和2560 img更高的像素时,它应该使用1920
图像吗? 我在这里误会什么吗?
编辑:行为在最新版本的Chrome中也发生了,除了原始问题之外,它每次都在加载2560
图像以及较小的图像之外 !
edit2: Safari的最新版本与Firefox的行为相同。
edit3:找到一个由其他人测试的小提琴 。 它的行为方式相同( 在浏览器宽度为图像大小的50%之前,不使用较小的图像 )。 这是一个错误吗? 或预期的功能srcset
和sizes
?
好的,对我来说有效的解决方案( 除了一个旧的Safari版本,它具有大致相同的支持 )是使用<picture>
标签,如下所示:
<picture class="backgroundContainer">
<source srcset="assets/water_bg_1024.jpg" media="(min-width: 0px) and (max-width:1024px)">
<source srcset="assets/water_bg_1920.jpg" media="(min-width: 1025px) and (max-width: 1920px)">
<source srcset="assets/water_bg_2560.jpg" media="(min-width: 1921px)">
<img class="backgroundImage" onload="imageLoaded(this)" src="assets/water_bg_1920.jpg" alt="">
</picture>
它将在所有最新版本的浏览器上的正确断点处正确加载所有图像。
我必须更加明智地工作,使用媒体查询并在size上设置sizes
。 我在iPhone上看到到2560w的img突破,但这是因为视网膜的像素密度。 为了使断点更紧密,您需要添加更多的媒体查询。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>sizes</title> </head> <body> <img src="http://placehold.it/1024x576/000/fff?text=1024w" sizes="(min-width: 36em) 33.3vw, 100vw" srcset="http://placehold.it/2560x1280/00f/fc0?text=2560w 2560w, http://placehold.it/1920x1080/e00/fcf?text=1920w 1920w, http://placehold.it/1024x576/000/fff?text=1024w 1024w" /> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.