HTML - DOM樣式物件textAlign屬性



HTML DOM 樣式物件 **textAlign** 屬性設定或返回塊級元素內文字內容的水平對齊方式。

語法

設定 textAlign 屬性
object.style.textAlign= "left | right | center | justify | initial | inherit";
獲取 textAlign 屬性
object.style.textAlign;

屬性值

描述
left 這是預設值,將文字左對齊。
right 將文字右對齊。
center 將文字居中對齊。
justify 將文字對齊方式設定為兩端對齊。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示元素內文字的水平對齊方式。

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

以下示例將 div 元素內的 p 元素的對齊方式設定為 **right**、**center** 和 **justify**。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object align Property
    </title>
    <style>
        #align {
        border: 1px solid #04af2f;
    }
    </style>
</head>
<body>
    <p>Click to change text alignment.</p>
    <button onclick="fun()">Right Align</button>
    <button onclick="funTwo()">Center Align</button>
    <button onclick="funThree()">Justify Align</button>
    <div  id="align">
        <p>
            JavaScript is a lightweight, interpreted 
            programming language. It is commonly used
            to create dynamic and interactive elements
            in web applications. JavaScript is very easy
            to implement because it is integrated with 
            HTML. It is open and cross-platform.
            This JavaScript tutorial has been designed 
            for beginners as well as working professionals 
            to help them understand the basic to advanced 
            concepts and functionalities of JavaScript. 
            It covers most of the important concepts 
            related to JavaScript such as operators, control
            flow, functions, objects, OOPs, Asynchronous 
            JavaScript, Events, DOM manipulation and much more.
        </p>   
    </div>       
    <script>
        function fun(){
            document.getElementById("align")
                .style.textAlign="right"
        }
        function funTwo(){
            document.getElementById("align")
                .style.textAlign="center"
        }
        function funThree(){
            document.getElementById("align")
                .style.textAlign="justify"
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
textAlign 是 1 是 12 是 1 是 1 是 3.5
html_dom_style_object_reference.htm
廣告