Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเปลี่ยนขนาดฟอนต์ข้อความด้วย JavaScript

ใช้เมธอด fontsize() ของ String กำหนดขนาดฟอนต์ เหมือนแท็ก <font size="..."> (deprecated ใน HTML5)

ตัวอย่าง

<html>
  <head>
    <title>JavaScript String fontsize() Method</title>
  </head>
  <body>
    <script>
      var str = new String("Demo Text");
      document.write(str.fontsize(10));
      alert(str.fontsize(10));
    </script>
  </body>
</html>

ผลลัพธ์

<font size="10">Demo Text</font>

⚠️ Legacy method – <font> tag deprecated ใช้ CSS แทน:

// CSS (แนะนำ)
.element { font-size: 1.5rem; } /* หรือ px, em, % */

// JavaScript แบบสมัยใหม่
element.style.fontSize = "1.5rem";

Font size units

Unitคำอธิบาย
pxพิกเซล (fixed)
emrelative to parent font-size
remrelative to root (html) font-size
%เปอร์เซ็นต์ของ parent
vw/vhเปอร์เซ็นต์ของ viewport