HTML - DOM樣式物件fontSize屬性



HTML DOM 樣式物件**fontSize**屬性設定或返回文字的字型大小。

語法

設定fontSize屬性
object.style.fontSize= "value | initial | inherit";
獲取fontSize屬性
object.style.fontSize;

屬性值

描述
xx-small
x-small
small
medium
large
x-large
xx-large
表示預定義的文字大小。
smaller 將字型大小減小1個相對單位。
larger 將字型大小增加1個相對單位。
長度單位 指定長度單位的字型大小。
百分比 指定百分比的字型大小。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

返回一個字串值,表示元素的字型大小屬性。

HTML DOM 樣式物件“fontSize”屬性示例

以下示例在p元素中設定不同的文字大小值。

使用預定義值設定字型大小

在此示例中,我們使用預定義的字型大小值來設定文字的字型大小。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object fontSize Property
    </title>
</head>
<body>
    <p>Click to change font size.</p>
    <button onclick="fun()">Xx-Small</button>
    <button onclick="small()">Small</button>
    <button onclick="medium()">Medium</button>
    <button onclick="large()">Large</button>
    <button onclick="xlarge()">X-Large</button>
    <p id="font">Welcome to Tutorials Point.</p>
    <script>
        function fun() {
            document.getElementById("font")
                .style.fontSize= "xx-small";
        }
        function small() {
            document.getElementById("font")
                .style.fontSize= "small";
        }
        function medium() {
            document.getElementById("font")
                .style.fontSize= "medium";
        }
        function large() {
            document.getElementById("font")
                .style.fontSize= "large";
        }
        function xlarge() {
            document.getElementById("font")
                .style.fontSize= "x-large";
        }
    </script>
</body>
</html>

使用長度值設定字型大小

在此示例中,我們以畫素為單位指定字型大小,以及smaller和larger屬性值。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object fontSize Property
    </title>
</head>
<body>
    <p>Click to change font size.</p>
    <button onclick="smaller()">Smaller</button>
    <button onclick="larger()">Larger</button>
    <button onclick="fun()">Change in Length</button>
    <p id="font">Welcome to Tutorials Point.</p>    
    <script>
        function smaller() {
            document.getElementById("font")
                .style.fontSize= "smaller";
        }
        function larger() {
            document.getElementById("font")
                .style.fontSize= "larger";
        }
        function fun() {
            document.getElementById("font")
                .style.fontSize= "30px";
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
fontSize 是 1 是 12 是 1 是 1 是 7
html_dom_style_object_reference.htm
廣告