Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTML系列之img的srcset的作用 #8

Open
yuanyuanbyte opened this issue Nov 12, 2021 · 0 comments
Open

HTML系列之img的srcset的作用 #8

yuanyuanbyte opened this issue Nov 12, 2021 · 0 comments
Assignees

Comments

@yuanyuanbyte
Copy link
Owner

img的srcset的作用

img 元素的 srcset 属性用于浏览器根据宽、高和像素密度来加载相应的图片资源。

属性格式:图片地址 宽度描述w 像素密度描述x,多个资源之间用逗号分隔。例如:

<img src="small.jpg " srcset="big.jpg 1440w, middle.jpg 800w, small.jpg 1x" />

上面的例子表示浏览器宽度达到 800px 则加载 middle.jpg ,达到 1400px 则加载 big.jpg。注意:像素密度描述只对固定宽度图片有效。

img 元素的 size 属性给浏览器提供一个预估的图片显示宽度。

属性格式:媒体查询 宽度描述(支持px),多条规则用逗号分隔。

<img src="images/gun.png" alt="img元素srcset属性浅析"
     srcset="images/bg_star.jpg 1200w, images/share.jpg 800w, images/gun.png 320w"
     sizes="(max-width: 320px) 300w, 1200w"/>

上面的例子表示浏览器视口为 320px 时图片宽度为 300px,其他情况为 1200px。

还有哪一个标签能起到跟srcset相似作用?(追问)

<picture>:picture 元素
HTML <picture> 元素通过包含零或多个 <source> 元素和一个 <img> 元素来为不同的显示/设备场景提供图像版本。浏览器会选择最匹配的子 <source> 元素,如果没有匹配的,就选择 <img> 元素的 src 属性中的URL。然后,所选图像呈现在<img>元素占据的空间中。

<!--Change the browser window width to see the image change.-->

<picture>
    <source srcset="/media/cc0-images/surfer-240-200.jpg"
            media="(min-width: 800px)">
    <img src="/media/cc0-images/painted-hand-298-332.jpg" alt="" />
</picture>

要决定加载哪个URL,用户代理检查每个 的 srcset、media 和 type 属性,来选择最匹配页面当前布局、显示设备特征等的兼容图像。

还有什么能起到跟srcset相似作用?(追问)

css image-set()

body {
    background-image: -webkit-image-set( url(../images/pic-1.jpg) 1x, url(../images/pic-2.jpg) 2x, url(../images/pic-3.jpg) 600dpi);
    background-image:         image-set( url(../images/pic-1.jpg) 1x, url(../images/pic-2.jpg) 2x, url(../images/pic-3.jpg) 600dpi);
}

上述代码将会为普通屏幕使用 pic-1.jpg,为高分屏使用 pic-2.jpg,如果更高的分辨率则使用 pic-3.jpg,比如印刷。

@yuanyuanbyte yuanyuanbyte self-assigned this Nov 12, 2021
@yuanyuanbyte yuanyuanbyte changed the title HTML系列之img的srcset的作用 (追问) HTML系列之img的srcset的作用 Nov 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant