HTMLImageElement: sizes 属性
HTMLImageElement 属性 sizes 允许您为一组媒体条件中的 图像指定布局宽度。这提供了在文档状态发生变化以匹配不同媒体条件时,自动选择不同图像(甚至不同方向或纵横比的图像)的能力。
每个条件都使用 媒体查询使用的相同条件格式指定。
值
一个字符串,包含逗号分隔的源大小描述符列表,后跟一个可选的备用大小。每个源大小描述符由媒体条件组成,然后是至少一个空格字符,然后是当媒体条件评估为 true 时要用于图像的源大小值。您可以使用值 auto 来替换整个大小列表或列表中的第一个条目。有关 sizes 属性语法的更多信息,请参阅 <img>。
示例
选择适合窗口宽度的图像
在此示例中,创建了一个类似博客的布局,显示了一些文本和一个图像,该图像根据窗口的宽度指定了三个大小点。还提供了图像的三个版本,并指定了它们的宽度。浏览器会获取所有这些信息,并选择一个最能满足指定值的图像和宽度。
图像的确切使用方式可能取决于浏览器和用户显示器的像素密度。
示例底部的按钮可以让您实际修改 sizes 属性,在 40em 和 50em 之间切换图像的最大三个宽度。
HTML
html
<article>
<h1>An amazing headline</h1>
<div class="test"></div>
<p>
This is even more amazing content text. It's really spectacular. And
fascinating. Oh, it's also clever and witty. Award-winning stuff, I'm sure.
</p>
<img
src="new-york-skyline-wide.jpg"
srcset="
new-york-skyline-wide.jpg 3724w,
new-york-skyline-4by3.jpg 1961w,
new-york-skyline-tall.jpg 1060w
"
sizes="(50em <= width <= 60em) 50em,
(30em <= width < 50em) 30em,
(width < 30em) 20em"
alt="The New York City skyline on a beautiful day, with the One World Trade Center building in the middle." />
<p>
Then there's even more amazing stuff to say down here. Can you believe it? I
sure can't.
</p>
<button id="break40">Last Width: 40em</button>
<button id="break50">Last Width: 50em</button>
</article>
CSS
css
article {
margin: 1em;
max-width: 60em;
min-width: 20em;
border: 4em solid #880e4f;
border-radius: 7em;
padding: 1.5em;
font:
16px "Open Sans",
"Verdana",
"Helvetica",
"Arial",
sans-serif;
}
article img {
display: block;
max-width: 100%;
border: 1px solid #888888;
box-shadow: 0 0.5em 0.3em #888888;
margin-bottom: 1.25em;
}
JavaScript
JavaScript 代码处理了两个按钮,它们允许您在 40em 和 50em 之间切换第三个宽度选项;这是通过处理 click 事件来完成的,使用 JavaScript 字符串 replace() 方法替换 sizes 字符串的相关部分。
js
const image = document.querySelector("article img");
const break40 = document.getElementById("break40");
const break50 = document.getElementById("break50");
break40.addEventListener(
"click",
() => (image.sizes = image.sizes.replace(/50em,/, "40em,")),
);
break50.addEventListener(
"click",
() => (image.sizes = image.sizes.replace(/40em,/, "50em,")),
);
结果
最好在 自己的窗口中查看此页面,以便您可以完全调整大小。
规范
| 规范 |
|---|
| HTML # dom-img-sizes |
浏览器兼容性
加载中…