HTML - DOM 元素 dir 屬性



dir 屬性提供了一種訪問 HTML 中任何元素的 dir 屬性值的方法,用於設定和檢索。此屬性決定文字的方向性,指定元素的內容應從左到右 (LTR) 還是從右到左 (RTL) 顯示。

語法

設定 dir 屬性
element.dir = "value";
獲取 dir 屬性
var direction = element.dir;

屬性

屬性值 描述
RTL 確定元素內容的從右到左方向。
LTR 確定元素內容的從左到右方向。
auto 自動確定文字方向。

返回值

此屬性返回一個“字串”,表示元素內文字的方向性。

HTML DOM 元素“dir”屬性示例

以下是一些 dir 屬性在各種用例中的示例,其中該屬性可用於控制 HTML 元素內文字的方向性。

將文字方向設定為從右到左 (RTL)

dir 屬性 設定為“rtl”,表示段落的文字方向為從右到左。此段落內的文字將從右到左顯示。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Right-to-Left (RTL)
    </title>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">dir Property
    <br><br> 
        Setting Text Direction to Right-to-Left (RTL)
    </h3> 
    <p dir="rtl">
        This text direction is right-to-left.
    </p>
</body>

</html>

動態更改文字方向

此示例演示如何使用 JavaScript 動態更改元素的文字方向,包括一個按鈕,該按鈕可在從左到右 (LTR) 和從右到左 (RTL) 之間切換段落的文字方向。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>
        Dynamically Changing Text Direction
    </title>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">dir Property
    <br><br> 
        Dynamically Changing Text Direction 
    </h3>  

    <button onclick="changeDirection()">
    Toggle Direction
    </button>

    <p id="text" dir="ltr">
    This text direction can be toggled.
    </p>
    <script>
        function changeDirection() {
            var textElement = 
            document.getElementById("text");
            if (textElement.dir === "ltr") {
                textElement.dir = "rtl";
            } else {
                textElement.dir = "ltr";
            }
        }
    </script>
</body>

</html>

使用繼承進行文字方向

在此示例中,<div> 元素使用 dir 屬性將其文字方向設定為從右到左 (RTL)。<p> 元素在 div 內繼承此文字方向性,以從右到左顯示文字。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Using Inheritance for Text Direction
    </title>
</head>

<body>
    <h2 align = "center">HTML - DOM Element </h2>
    <h3 align = "center">dir Property
    <br><br> 
    Using Inheritance for Text Direction
    </h3>   
    <div dir="rtl">
        <p>
            This paragraph inherits the text 
            direction from its parent.
        </p>
    </div>    
</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
dir
html_dom_element_reference.htm
廣告