仅在较小的屏幕上显示图像

Display image only on smaller screens

本文关键字:显示 显示图 图像 屏幕      更新时间:2023-09-26

有人可以帮我修改下面的代码以仅在移动视图中显示图像吗?现在,它总是可见的。

<style type="text/javascript">
      .icon-xyz
      {float: left; width: 22px;cursor: pointer;background: none;}
      @media only screen and (max-device-width: 568px) and (min-device-width: 320px) and (orientation: portrait)
     {.icon-xyz {float: left;width: 22px;background: none;cursor: pointer;padding: 0 13px !important;}}
</style>

以下是添加图像的脚本:

$(document).ready(function() {
      var loc = window.location;
      if (loc.toString().toUpperCase().indexOf('/home/') > -1)
      {
      $("#icon-xyz").css("background", "url(/images/Icon1.png) no-repeat");
      if($.cookie("lang") == "es")
      {
      $("#icon-xyz").css("background", "url(/images/Icon2.png) no-repeat");
      }
      }
});

https://jsfiddle.net/ad8bc8tv/1/

由于您使用的是max-device-widthmin-device-width因此您将无法在桌面浏览器上测试此媒体查询,因为它只会在与这些参数匹配的设备上执行。

这可能是它似乎不起作用的原因之一。

要在桌面环境中进行测试,请尝试改用max-widthmin-width,因为它们与浏览器窗口的大小有关,而不是设备的屏幕大小。

事实上,用他们的话来说,谷歌强烈反对使用*-device-width媒体查询,原因与旧版浏览器报告和适应性有关(更多详细信息)。

就解决方案而言,这里有一个可能适合您的 CSS 方法:

.icon-xyz {
  display: none;
}
@media only screen and (min-width: 320px) and (max-width: 568px) and 
   (orientation: portrait) { .icon-xyz { display: inline; } }
<img class="icon-xyz" src="http://i.imgur.com/60PVLis.png" width="100" height="100" alt="">

js小提琴