HTML - DOM Style 物件 backgroundPosition 屬性



HTML DOM Style 物件 **backgroundPosition** 屬性設定或返回元素的背景影像位置。

語法

以下是獲取或設定 backgroundPosition 屬性的語法。

設定 backgroundPosition 屬性
object.style.backgroundPosition = value;
獲取 backgroundPosition 屬性
object.style.backgroundPosition;

屬性值

描述
頂部左側
頂部居中
頂部右側
中間左側
中間居中
中間右側
底部左側
底部居中
底部右側
它使用關鍵詞指定背景影像的位置。如果只指定一個值,則預設另一個值為“居中”。
x% y% 它使用百分比指定背景影像的位置,其中 x 表示水平位置,y 表示垂直位置。0% 0% 表示左上角,而 100% 100% 表示右下角。當只指定一個值時,預設另一個值為 50%(居中)。
xpos ypos 它使用畫素或任何其他 CSS 測量單位指定背景影像的位置,其中 x 表示水平位置,y 表示垂直位置。0 0 表示左上角,而 100 100 表示右下角。當只指定一個值時,預設另一個值為居中。
初始值 用於將此屬性設定為其預設值。
繼承 用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示背景影像的位置。

HTML DOM Style 物件“backgroundPosition”屬性示例

以下示例說明了使用不同方法定位背景。

使用關鍵詞定位

在以下示例中,我們使用了關鍵詞來定位背景影像。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object backgroundPosition Property
    </title>
    <style>
        body {
            background: #f3f3f3 url('/html/images/logo.png') no-repeat;
            height: 300px;
            width: 300px;
        }
    </style>
</head>
<body>
    <p>Click to change positioning.</p>
    <button onclick="topcen()">Top Center</button>
    <button onclick="bottomleft()">Bottom Left</button>
    <button onclick="centerright()">Center Right</button>
    <script>
        function topcen(){
            document.body.style.backgroundPosition="top";
        }
        function bottomleft(){
            document.body.style.backgroundPosition="bottom left";
        }
        function centerright(){
            document.body.style.backgroundPosition="center right";
        }
    </script>
</body>
</html>

使用百分比定位

在以下示例中,我們使用了百分比來定位背景影像。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Style Object backgroundPosition Property</title>
    <style>
        body {
            background: #f3f3f3 url('/html/images/logo.png') no-repeat;
            height: 300px;
            width: 300px;
        }
    </style>
</head>
<body>
    <p>Click to change positioning.</p>
    <button onclick="fun()">Change</button>
    <script>
        function fun(){
            document.body.style.backgroundPosition="74% 80%";
        }
    </script>
</body>
</html>

使用畫素定位

在以下示例中,我們使用了畫素來定位背景影像。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Style Object backgroundPosition Property</title>
    <style>
        body {
            background: #f3f3f3 url('/html/images/logo.png') no-repeat;
            height: 300px;
            width: 300px;
        }
    </style>
</head>
<body>
    <p>Click to change positioning.</p>
    <button onclick="fun()">Change</button>
    <script>
        function fun(){
            document.body.style.backgroundPosition="60px 60px";
        }
    </script>
</body>
</html>

支援的瀏覽器

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