:外部资源链接元素

2021-04-15  本文已影响0人  LRachel

HTML外部资源链接元素 (<link>) 规定了当前文档与外部资源的关系。该元素最常用于链接样式表,此外也可以被用来创建站点图标(比如PC端的“favicon”图标和移动设备上用以显示在主屏幕的图标) 。

要链接一个外部的样式表,你需要像这样在你的<head>中包含一个<link>元素:

<link href="main.css" rel="stylesheet">

在这个简单的例子中,使用了 href 属性设置外部资源的路径,并设置 rel 属性的值为“stylesheet”(样式表)。rel 表示“关系 (relationship) ”,

这里是一个网站图标的链接:<link rel="icon" href="favicon.ico">

还有一些其它的与图标相关的rel值,主要用于表示不同移动平台上特殊的图标类型,例如:

<link rel="apple-touch-icon-precomposed" sizes="114x114"      href="apple-icon-114.png" type="image/png">


你也可以提供一个媒体类型,或者在media属性内部进行查询;这种资源将只在满足媒体条件的情况下才被加载进来。

<link href="print.css" rel="stylesheet" media="print"> <link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)">

提供用于不通用法上下文的图标

您可以在同一页面上包含指向多个不同图标的链接,浏览器将使用rel和sizes 值作为提示来选择最适合其特定上下文的图标。

<!-- third-generation iPad with high-resolution Retina display: -->

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="favicon144.png">

<!-- iPhone with high-resolution Retina display: -->

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon114.png">

<!-- first- and second-generation iPad: -->

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon72.png">

<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->

<link rel="apple-touch-icon-precomposed" href="favicon57.png">

<!-- basic favicon -->

<link rel="icon" href="favicon32.png">

通过媒体查询有条件地加载资源

您可以在media属性中提供媒体类型或查询; 然后,只有在媒体条件为true时,才会加载此资源。 例如

<link href="print.css" rel="stylesheet" media="print">

<link href="mobile.css" rel="stylesheet" media="all">

<link href="desktop.css" rel="stylesheet" media="screen and (min-width: 600px)">

<link href="highres.css" rel="stylesheet" media="screen and (min-resolution: 300dpi)">

样式表加载事件

你能够通过监听发生在样式表上的事件知道什么时候样式表加载完毕。同样的,你能够通过监听error事件检测到是否在加载样式表的过程中出现错误。

<script>functionsheetLoaded(){// Do something interesting; the sheet has been loaded}functionsheetError(){alert("An error occurred loading the stylesheet!");}</script><linkrel="stylesheet"href="mystylesheet.css"onload="sheetLoaded()"onerror="sheetError()">

上一篇 下一篇

猜你喜欢

热点阅读