簡體   English   中英

如何使用純JavaScript動態更改div的背景圖像

[英]How to dynamically change a background image of a div using pure javascript

  • 使用javascript更改主體的背景圖像的語法是什么
  • 如何解決y.style.background = '' + "url(1.jpg) no-repeat" + '';

標記:

<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            //this is the style for body tag
            background: url("heart.png") no-repeat;
            color: red;
        }
    </style>
</head>

<body>
    <h3><p id="hello">This Is Heart.</p>
        </h3>
    <button onclick="myFunction()">Try it</button>
    <script>
        function myFunction() {
                var x = document.getElementById("hello"); //this is id of paragraph
                var y = document.getElementsByTagName("body"); //id of background element
                var z = document.getElementById('myImg');
                y.style.background = '' + "url(1.jpg) no-repeat" + ''; //y error what will be the code to replace background-image of div
    </script>
</body>

</html>

如果要更改body的backgorund圖像,可以執行此操作

document.body.style.backgroundImage = "url(1.jpg)";
document.body.style.backgroundRepeat = "no-repeat";
//OR
document.body.style.background = "url(1.jpg) no-repeat";

更新

document.getElementsByTagName("body")返回帶有標簽body的元素的集合(如數組)。 由於只有一個主體,因此我們將使用document.getElementsByTagName("body")[0]

參見文檔。

您的主要問題可能是(盡管您可能想向問題中添加實際的錯誤消息) getElementsByTagName()返回的是DOM元素數組,而不是單個元素。 因此,如果您更改為

var y = document.getElementsByTagName("body")[0]; //array will contain a single element
y.style.background = 'url(1.jpg) no-repeat'; //No need for your funky empty string concatenation

我認為你應該很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM