HTML - DOM Style 物件 background 屬性



HTML DOM Style 物件的 **background** 屬性是一個簡寫屬性,它設定或返回元素的最多 8 個獨立的背景屬性。

DOM 屬性和對應的 CSS 屬性

語法

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

設定 background 屬性
object.style.background= "color | image | repeat | attachment | position | size | origin | clip | initial | inherit";
獲取 background 屬性
object.style.background;

屬性值

描述
attachment 它設定影像是在滾動時滾動還是保持固定。其預設值為 **scroll**。
color 它設定元素的背景顏色。其預設值為 **transparent**。
image 它設定元素的背景影像。其預設值為 **none**。
position 它設定背景影像的起始位置。其預設值為 **0% 0%**。
repeat 它設定背景影像應如何在 x 和 y 軸上重複。其預設值為 **repeat**。
clip 它設定背景影像的繪製區域。其預設值為 **border-box**。
origin 它設定背景的原點,可以是從邊框的開始、邊框內部或填充內部。其預設值為 **padding-box**。
size 它設定元素的背景影像的大小。其預設值為 **auto**。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示元素的背景。

HTML DOM Style 物件“background”屬性的示例

以下示例說明了 background 屬性的一些屬性。

向 Body 新增背景影像

在以下示例中,我們使用 background 屬性向 body 添加了一個影像。

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

更改 div 元素的背景

在以下示例中,我們已將 div 元素的背景顏色從紅色更改為綠色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object background Property
    </title>
    <style>
        #back {
            height: 400px;
            width: 400px;
            background-color: red;
            align-content: center;
        }
    </style>
</head>
<body>
    <p>Click to change background of div.</p>
    <button onclick="fun()">Change</button>
    <div id="back">Welcome to Tutorials Point.</div>
    <script>
        function fun() {
            document.getElementById("back")
            .style.background = "#04af2f no-repeat center"
        }
    </script>
</body>
</html>

更改文件的背景

在此示例中,使用 background 屬性的 **color** 屬性值,我們將顏色從紅色更改為綠色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object background Property
    </title>
    <style>
        #back {
            background-color: red;
            align-content: center;
            color: white;
        }
    </style>
</head>
<body>
    <p>Click to change background of div.</p>
    <button onclick="fun()">Change</button>
    <p id="back"> 
        Color of this paragraph is going to change.
    </p>
    <script>
        function fun() {
            document.getElementById("back")
            .style.background = "#04af2f"
        }
    </script>
</body>
</html>

支援的瀏覽器

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