iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 4
0
Modern Web

AMP系列 第 4

AMP(Lession 4) - 字型

  • 分享至 

  • twitterImage
  •  

AMP 中設定字型

誠如前面所說的, AMP 並不希望引入外部的檔案。可是…預設的字體就是不得人疼,我就是要另外載入別的字體呀!!

怎麼辦呢?!

有2種方法

方法一:使用 <LINK>

例如: <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">

方法一:使用 @font-face

  1. Step 1 - 請引入 amp-font 這個元件

<script async custom-element="amp-font" src="https://cdn.ampproject.org/v0/amp-font-0.1.js"></script>

  1. Step 2 - 使用 <style amp-custom> tag ,如 CSS 語法那般,設定 @font-face
<style amp-custom>
  @font-face {
    font-family: 'my font name'; /*基本項目*/
    font-style: normal;
    font-weight: 400;
    src: url(fonts/MyFontName.ttf) format('truetype'); /*基本項目*/
  }
  ... /* 視需求設定1組 ~ 多組 */
</style>
  1. Step 3 - 在 <style amp-custom> tag 中,設定 font-family
<style amp-custom>
.comicamp-loaded .use-my-font {
  font-family: 'my font name', serif, sans-serif;
}
</style>
  1. Step 4 - 善用 <amp-font> tag 設定,使用成功載入的字體
 <amp-font
      layout="nodisplay"
      font-family="My Font Name"
      timeout="3000"
      on-error-remove-class="my-font-loading"
      on-error-add-class="my-font-missing"></amp-font>
  <amp-font
      layout="nodisplay"
      font-family="My Other Font"
      timeout="1000"
      on-load-add-class="my-other-font-loaded"
      on-load-remove-class="my-other-font-loading"></amp-font>

如上範例;

4.1. layout - 一定要是 nodisplay

4.2. font-family - 字型名稱

4.3. timeout - 非必要項目,預設3000,單位 ms

4.4. on-load-add-class & on-load-remove-class - 非必要項目,於字型載入成功時觸發,對於 documentElement 或 body 元件做 class name 的切換。

4.4. on-error-add-class & on-error-remove-class - 非必要項目,於字型載入錯誤或 timeout 時觸發,對於 documentElement 或 body 元件做 className 的切換。


參考來源:


上一篇
AMP(Lession 3) - 使用AMP做RWD
下一篇
AMP(Lession 5) - 依區塊而改變文字大小 amp-fit-text
系列文
AMP30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Dylan
iT邦新手 3 級 ‧ 2018-10-16 16:47:08

感謝分享!

不過 Step 3 - amp-custom 似乎打錯成 smp-custom

majo2013 iT邦新手 4 級 ‧ 2018-10-16 18:54:10 檢舉

真的(汗) 謝謝你

我要留言

立即登入留言