简体   繁体   English

如何使用纯JavaScript动态更改div的背景图像

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

  • What will be the syntax to change the background-image of body using javascript 使用javascript更改主体的背景图像的语法是什么
  • How to fix the error in line y.style.background = '' + "url(1.jpg) no-repeat" + ''; 如何解决y.style.background = '' + "url(1.jpg) no-repeat" + '';

Markup : 标记:

<!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>

If you want to change the backgorund image of your body , you can do this 如果要更改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";

Update : 更新

document.getElementsByTagName("body") returns a collection(like an array) of elements with tag body . document.getElementsByTagName("body")返回带有标签body的元素的集合(如数组)。 Since we have only one body we will use document.getElementsByTagName("body")[0] . 由于只有一个主体,因此我们将使用document.getElementsByTagName("body")[0]

See the docs. 参见文档。

Your main problem is probably (though you might want to add the actual error message to your question) that getElementsByTagName() returns an array of DOM elements and not a single one. 您的主要问题可能是(尽管您可能想向问题中添加实际的错误消息) getElementsByTagName()返回的是DOM元素数组,而不是单个元素。 So if you change to 因此,如果您更改为

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

I think you should be good. 我认为你应该很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM