javascript - 多个设备的图像响应?

标签 javascript jquery html css

这是我的 html 代码:

<picture>
<source srcset="480_smaller_landscape.jpg" media="(max-width: 480px) and (orientation: landscape)">
<source srcset="776_smaller_portrait.jpg" media="(max-width: 776px) and (orientation: portrait)">
<source srcset="1080_default_landscape.jpg" media="(min-width: 1080px) and (orientation: landscape)">
<source srcset="1926_default_portrait.jpg" media="(min-width: 1926px) and (orientation: portrait)">
<img srcset="default_landscape.jpg" alt="My default image">
</picture>

我的问题是: 如果我将此代码用于多个设备的图像响应..

一次发送多少个请求?对于所有图像还是仅对于特定设备所需的图像...?

示例:如果我为平板电脑 (776px) 加载此图片页面,则只会加载“776_smaller_portrait.jpg”。

所有图像将立即加载但只显示“776_smaller_portrait.jpg”

我想做什么:

我想为特定设备显示特定图像,图像将像

<img srcset="file_path/device_resulation_image_name.jpg" alt="My default image">

最佳答案

这很容易测试,只需在加载页面时打开开发者工具并在“网络”选项卡上进行设置即可。

<picture>
<source srcset="480_smaller_landscape.jpg" media="(max-width: 480px) and (orientation: landscape)">
<source srcset="776_smaller_portrait.jpg" media="(max-width: 776px) and (orientation: portrait)">
<source srcset="1080_default_landscape.jpg" media="(min-width: 1080px) and (orientation: landscape)">
<source srcset="1926_default_portrait.jpg" media="(min-width: 1926px) and (orientation: portrait)">
<img srcset="default_landscape.jpg" alt="My default image">
</picture>

enter image description here

但是,更好的方法是使用 CSS 媒体查询,这样您的 HTML 就不会因样式内容而变得杂乱无章。在这种情况下,您将拥有一个元素(可能是 div)并使用媒体查询有条件地为该元素设置 background:url() 属性。这是一个简单的例子。运行此代码段并将浏览器的大小从大调整为小,然后再调整回来。

#responsive { background-size:contain; }

@media screen and (max-width:800px) {
  #responsive {
    background-image: url("https://free.clipartof.com/10-Free-Smiley-Face-With-Black-Eye.jpg");
  }
}

@media screen and (min-width:801px) {
  #responsive {
    background-image:url("https://static-s.aa-cdn.net/img/ios/736026129/e17c5fe0e78bd561ba719c2a38ad85b6?v=1");
  }
}
<div id="responsive"></div>

关于javascript - 多个设备的图像响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46940233/

相关文章:

Javascript,如何重新创建选择/范围?

jquery - 为什么 .prop ("selected",true) 不工作,而 .attr() 或 .addClass() 工作?

javascript - 使用已加载脚本的功能

jquery - 过滤掉包含多个 css 类的 tr

html - 更改 CSS 中的边框长度

javascript - 从图像中读取文本

JavaScript 窗口全局对象

javascript - ng-bootstrap datepicker 无法在选择之前设置默认日期

javascript - Jquery UI - 拖动旋转元素时出现问题

javascript - 仅在 Firefox 中显示无样式内容 (FOUC)