javascript - 在小屏幕上隐藏/显示图像

标签 javascript angular angular-material angular-material2

我的前端使用 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/

相关文章:

java - 禁止 javascript 在 javafx webview 中运行

javascript - 需要帮助显示()隐藏()底部序列导航取决于选择输入

javascript - 在对象数组中搜索匹配的键/值对的快速方法

angular - 错误 TS1192 : Module '" A. 模块“”没有默认导出

angularfire2 - 如何在 firebase 中使用多个 where 子句?

Angular Material 日期选择器最小和最大日期验证消息

javascript - 为什么在渲染时调用 onClick?

javascript - "module": "esnext" in tsconfig. json没有去掉Dynamic Lazy load模块报错

angular - 自 Angular/Material 从 5 升级到 6 以来,自定义 native 日期适配器不再起作用

angular - Material datePicker( Angular )中的多个日期选择