DIV CSS 佈局教程網

用 jQuery 動態設定 font-size 的寫法與完整範例
編輯:JQuery特效代碼     

改字級只需要一行 css():

$("#hovertree").css("font-size", "50px");

這行的意思是把 id 為 hovertree 的元素字級設為 50px。

可互動的完整範例

<div>
  <span id="hovertree">
    這是文字內容,何問起, hovertree.com
  </span>
  <button id="btnhovertree">設置 span 的 font-size 為 50px</button>
</div>

<script src="https://down.hovertree.com/jquery/jquery-1.12.3.min.js"></script>
<script>
  $("#btnhovertree").on("click", function () {
    $("#hovertree").css("font-size", "50px");
  });
</script>

可直接存成單一檔案的版本

<!DOCTYPE html>
<html>
<head>
  <title>jQuery 設置 font-size - 何問起</title>
  <style>
    #hovertree { font-size: 16px; }
  </style>
</head>
<body>
  <div>
    <span id="hovertree">這是文字內容,何問起, hovertree.com</span>
    <button id="btnhovertree">設置 span 的 font-size 為 50px</button>
  </div>

  <script src="https://down.hovertree.com/jquery/jquery-1.12.3.min.js"></script>
  <script>
    $("#btnhovertree").on("click", function () {
      $("#hovertree").css("font-size", "50px");
    });
  </script>
</body>
</html>

幾個實務上的提醒

  • 要帶單位:css("font-size", "50px") 可以,直接寫數字 50 在部分情況下會被補上 px,但遇到 line-height 這類無單位屬性時就容易出錯,養成寫單位的習慣比較安全。
  • 駝峰寫法也可以:css("fontSize", "50px") 與 css("font-size", "50px") 等效,jQuery 會自動轉換。
  • 相對單位更靈活:若希望字級能隨容器縮放,改用 em、rem 或 % 會比固定 px 好維護。
  • 批次設定:一次改多個屬性時用物件寫法更清楚:$("#hovertree").css({ "font-size": "50px", color: "#f60" })。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved