如何在移动设备和桌面设备上显示不同的图片

15

嗨,请问有人知道如何在桌面和移动设备上显示不同的横幅图片吗?这是我的代码:

HTML:

<div class="row">
    <img src="image\bannerimages\Career.png" class="img-responsive careerpage">
    <h2 class="careerbannertext">LIFE AT TEKNOTRAIT</h2>
    <h2 class="careerbannertext1">Are you fanatically driven and ready to take on some of the best challenges the industry has to offer? </h2>
    <h2 class="careerbannertext2">Come join us,be inspired to do the best work of your life!</h2>       
</div>

目前在我的桌面版本中显示这张图片,我需要在移动版本中更改为另一张图片。


3
媒体查询...尝试在SO上搜索此内容。 - Paulie_D
@Paulie_D 但是为了隐藏桌面上的图片,我需要在媒体查询中使用display none,然后我使用的那张图片就不会显示出来。 - user6728960
1
是的,那么你需要准备另一张图片来适配移动端。 - Paulie_D
1
最佳示例:https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_picture - Suresh Kamrushi
4个回答

67

您可以尝试这个:

<picture>
   <source 
      media="(min-width: 650px)"
      srcset="images/img1.png">
   <source 
      media="(min-width: 465px)"
      srcset="images/img2.png">
   <img src="images/img-default.png" 
   alt="a cute kitten">
</picture>

图片标签仍然存在,因此您可以为不支持picture标签的其他浏览器设置默认图像。


srcset 在 Internet Explorer 上不兼容:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/img - robskrob
20
因此,如果浏览器不支持它,它就会使用 <img src="images/img-default.png" 作为备用选项。 - Ron.Basco
1
这看起来很有趣,我打算在我的新主页上试一试。肯定会很棒的。 - Mohammed Joraid

6
你可以在移动设备上使用media属性,将其值设置为(orientation: portrait),在桌面设备上则设置为(orientation: landscape),以此来使用源元素。
例如:
<picture>
   <source 
      media="(orientation: landscape)"
      srcset="testlandscape.png">
   <source 
      media="(orientation: portrait)"
      srcset="testportrait.png">
      
 <img src="testlandscape.png" width="100%" height="auto">
</picture>

-2

使用这种方法代替。虽然我还在学习它,但它比这里提到的其他选项要好得多。除了仅使用HMTL完成外,它还不会在后台下载不需要的图像(例如,它不会下载高分辨率桌面图像并将其隐藏,就像使用CSS display:none一样)。


1
嘿,@sperch16。仅提供链接的答案是不够的,请将您的答案直接输入。 - f.khantsis
1
是的,不会这样做。解释整个过程需要占用5到10页的篇幅,而简单地复制和粘贴别人的帖子是低效的。这就是超链接发明的原因! - spercy16
除了这个答案是链接答案之外,链接本身也无法访问。 - tno2007

-2
我无法删除我的采纳答案,请不要使用它。 最好的方法是使用带有来源的标签图片,就像 Ron.Basco 的帖子一样:
<picture>
   <source 
      media="(min-width: 650px)"
      srcset="images/img1.png">
   <source 
      media="(min-width: 465px)"
      srcset="images/img2.png">
   <img src="images/img-default.png" 
   alt="a cute kitten">
</picture>

我的原始答案被接受了,但并不好,因为每个设备都会加载图片:

.img-responsive.mobile {
  display: none;
}

@media only screen and (max-device-width: 480px) {
  .img-responsive {
    display: none;
  }
  .img-responsive.mobile {
    display: block;
  }
}
<div class="row">
    <img src="image\bannerimages\Career.png" class="img-responsive careerpage">
    <img src="image\bannerimages\Career-mobile.png" class="img-responsive careerpage mobile">
    <h2 class="careerbannertext">LIFE AT TEKNOTRAIT</h2>
    ...       
</div>


41
这会在任何设备上加载两张图片(但只显示其中一张)。对性能影响很不好。 - alexander farkas
1
@alexanderfarkas 考虑到性能是我来到这里的唯一原因... - wedstrom
除非两个图像都是SVG格式且总大小不超过20KB,同时如果您需要为一些旧客户端仍然支持IE 11。但是,是的,未来将使用src集。 - Maximus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接