HTML - DOM樣式物件 backgroundImage 屬性



HTML DOM 樣式物件 **backgroundImage** 屬性設定或返回元素的背景圖片。

語法

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

設定 backgroundImage 屬性
object.style.backgroundImage= "url('URL') | none | initial | inherit";
獲取 backgroundImage 屬性
object.style.backgroundImage;

屬性值

描述
url('URL') 指定圖片位置。
none 預設值,指定不應用背景圖片。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示背景圖片。

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

以下示例說明如何設定和刪除文件中的背景圖片。

設定背景圖片

以下示例在文件中設定背景圖片。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object backgroundImage Property
    </title>
    <style>
        body {
            background-repeat: no-repeat;
            background-position: right;
        }
    </style>
</head>
<body>
    <p>Click to add background image.</p>
    <button onclick="fun()">Change</button>
    <script>
        function fun(){
            document.body.style.backgroundImage=
            "url('html/images/logo.png')";
        }
    </script>
</body>
</html>

刪除背景圖片

以下示例從文件中刪除已存在的背景圖片。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object backgroundImage Property
    </title>
    <style>
        body {
            background-image: url('/html/images/logo.png');
            background-repeat: no-repeat;
            background-position: right;
        }
    </style>
</head>
<body>
    <p>Click to remove background image.</p>
    <button onclick="fun()">Change</button>
    <script>
        function fun(){
            document.body.style.backgroundImage="none";
        }
    </script>
</body>
</html>

支援的瀏覽器

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