简体   繁体   English

如何在主体上添加div?

[英]How to append a div to the body?

I am supposed to assign .moon and .planet to the "planet" class and add a background colour to it, so I need to create a div. 我应该将.moon和.planet分配给“ planet”类,并为其添加背景色,所以我需要创建一个div。 I have no idea on how to append a div to the body. 我不知道如何将div附加到正文。

The code below shows what I'm currently trying. 下面的代码显示了我当前正在尝试的内容。 Please point out my mistake(s). 请指出我的错误。

 <html> <head> <meta charset="utf-8"> <title>Challenge: Create a solar system</title> <style> body { background-color: black; padding: 10px; } .planet { width: 100px; height: 100px; border-radius: 50%; text-align: center; padding: 10px; position: relative; } .moon { position: absolute; width: 30px; height: 30px; border-radius: 50%; background: rgb(237, 237, 237); } </style> </head> <body> <script> var bodyEl = document.querySelector("body"); for (var i = 0; i < planetsNode.length; i++) { var planetsNode = document.createElement("div"); planetsNode[i].className += "planet"; planetsNode.body.backgroundColor = "rgb(235, 12, 235)"; document.body.appendChild(planetsNode); } </script> </body> </html> 

You are accessing the variable 'planetsNode' before it gets created and you are accessing body from 'planetNode' element while assigning background color. 在创建变量'planetsNode'之前,您正在访问它,并且在分配背景色时正在从'planetNode'元素访问正文。

Hope this might help. 希望这会有所帮助。

<script>
 var body = document.querySelector("body");

 var planetsNode = document.createElement("div");       
 planetsNode.className = "planet";

 body.style.backgroundColor = "rgb(235, 12, 235)";
 body.appendChild(planetsNode);
</script>

I don't know why you are using loop. 我不知道你为什么要使用循环。

You are trying to access 'length' property of the 'planetsNode' variable before it has been created. 您试图在创建'planetsNode'变量之前访问'length'属性。 If you are looking to create a new div for each planet create an array of planets and loop through them. 如果要为每个行星创建一个新的div,请创建一个行星数组并循环遍历它们。

<script>
    var planets = [
        ["Mercury", "46.3, 46.3, 46.3"],
        ["Venus", "80.4, 78.4, 76.1"], 
        ["Earth", "34.9, 37.3, 51.4"], 
        ["Mars", "99.6, 52.9, 37.3"],
        ["Jupiter", "85.1, 74.9, 65.1"], 
        ["Saturn", "86.3, 73.7, 50.6"],
        ["Uranus", "76.5, 91.4, 92.5"],
        ["Neptune", "28.2, 47.5, 98.8"]
    ];

    for (var i = 0; i < planets.length; i++) {

        var planetNode = document.createElement("div");
        planetNode.style.backgroundColor = "rgb(" + planets[i][1] + ")";

        var nameNode = document.createTextNode(planets[i][0]);
        planetNode.appendChild(nameNode);

        var body = document.querySelector("body");
        body.appendChild(planetNode);
    }
</script>

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

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