首页 > 解决方案 > AppendChild 除了另一个元素

问题描述

我是 JS 新手——所以我直接请求道歉。

我正在使用 appendchild 创建一个简单的 div。这个动作是由一个按钮完成的。问题是每次我按下按钮时,它都会在前一个正方形下方创建一个新正方形 - 不是除此之外。除了它我该怎么做?

<html>
    <head>
        <title>RocketSeat - Challenge 1</title>
    </head>
    <body>
        <button onclick="MakeSquare()" style="margin-top: 100px;">Make a square</button>

    </body>
    <script>
        function MakeSquare(){
            const square = document.createElement('div')
            const elementBody = document.querySelector('body')
            square.style.backgroundColor ='red'
            square.style.width = '50px'
            square.style.height = '50px'
            square.style.marginTop= '50px'
            square.style.border = '1px solid red'
            elementBody.appendChild(square)
        }

    </script>
</html>

标签: javascripthtmlcss

解决方案


似乎是 CSS(样式)问题,试试这个:

<html>

<head>
  <title>RocketSeat - Challenge 1</title>
</head>

<body>
  <button onclick="MakeSquare()" style="margin-top: 100px;">Make a square</button>

</body>
<script>
  function MakeSquare() {
    const square = document.createElement('div')
    const elementBody = document.querySelector('body')
    square.style.backgroundColor = 'red'
    square.style.width = '50px'
    square.style.height = '50px'
    square.style.marginTop = '50px'
    square.style.border = '1px solid red'
    square.style.display = 'inline-block' // added display styling
    elementBody.appendChild(square)
  }
</script>

</html>


推荐阅读