Hide/show image on small screen

こ雲淡風輕ζ 提交于 2019-12-10 15:41:54

问题


I am using Angular material-2 for my frontend, I want to display different images for desktop and mobile screens

I have this code shown below

<div class="banner">
  <img [src]="images.desktopBanner"/>
  <img [src]="images.mobileBanner"/>
</div>

I want to display desktopBanner image in large devices and mobileBanner in small screens.

NOTE: marking display:none using media query is not the best solution as this might not display both the images together but if you check the network call it will still download both the images.


回答1:


I suggest you read these two articles:

  • Don’t use <picture> (most of the time)
  • Native Responsive Images

The crux of these articles explain use cases for both <picture> and <img srcset="...">.

Essentially, if you are trying to show the same image at different quality levels, which is a responsiveness use case, you should use an <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" />

If you want to show very different images, you are likely talking about art direction in which case, <picture> makes sense because:

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.

So syntax would resemble:

<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>

Both solutions have good support: everything but IE, as well as a way to fallback to regular, non-fancy rendering.




回答2:


Here's a solution using property innerWidth of the window DOM object :

isMobile() {
  return window.innerWidth <= 640;
}
<div class="banner">
    <img *ngIf="!isMobile()" [src]="images.desktopBanner"/>
    <img *ngIf="isMobile()" [src]="images.mobileBanner"/>
</div>

Here, images.mobileBanner will be displayed when browser's inner width is less of equal to 640px (tweak to your requirements...), images.desktopBanner will be used otherwise.



来源:https://stackoverflow.com/questions/51426376/hide-show-image-on-small-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!