我的前端使用 Angular material-2, 我想为桌面和移动屏幕显示不同的图像
我的代码如下所示
<div class="banner">
<img [src]="images.desktopBanner"/>
<img [src]="images.mobileBanner"/>
</div>
我想在大型设备上显示 desktopBanner 图像,在小屏幕上显示 mobileBanner。
注意:使用媒体查询标记 display:none 不是最佳解决方案,因为这可能不会同时显示两个图像,但如果您检查网络调用,它仍会下载两个图像。
最佳答案
我建议你阅读这两篇文章:
这些文章的关键解释了 <picture>
的用例和 <img srcset="...">
.
本质上,如果您试图以不同的质量级别显示相同的图像,这是一个响应性用例,您应该使用 <img srcset="...">
:
<img
src="swing-400.jpg"
sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
alt="Kettlebell Swing" />
如果您想展示截然不同的图像,您可能会谈论艺术指导,在这种情况下,<picture>
有道理,因为:
Why can’t we do art-direction with sizes/srcset?
By design, the sizes/srcset syntax takes into account the viewport’s width as well as the screen’s DPR. Adding art-direction into the same syntax would have meant that the web developer has to explicitly specify all the DPR and viewport width combinations in the markup.
That would have made the web developer’s job much more difficult and would have made the syntax much harder to grasp and significantly more verbose.
所以语法类似于:
<picture>
<source media="(min-width: 45em)" srcset="large.jpg">
<source media="(min-width: 32em)" srcset="med.jpg">
<img src="small.jpg" alt="The president giving an award.">
</picture>
这两种解决方案都有很好的支持:除了 IE 之外的所有内容,以及一种回退到常规、非花哨渲染的方法。
关于javascript - 在小屏幕上隐藏/显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51426376/