AppendChild помимо другого элемента - PullRequest
0 голосов
/ 02 августа 2020

Я JS newb ie - поэтому прошу извинений из первых рук.

Я использую 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>

Ответы [ 2 ]

1 голос
/ 02 августа 2020

Похоже на проблему 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>
0 голосов
/ 02 августа 2020

Это проблема стиля. В этом сценарии было бы проще отделить стиль от кода. Вы можете сделать это, присвоив ему класс. Я бы также приказал предоставить оболочку вокруг квадратов, чтобы вы могли лучше контролировать макет. Затем вы можете еще больше улучшить настройку, указав ему css переменных в оболочке, чтобы вы могли контролировать его стиль, если вам когда-либо понадобится. вот пример:

const setup = () => {
  makeSquare();
  makeSquare();
  makeSquare();
  
  changeSquareColorToPink();
  changeSquareDefaultColorToBlue();
}


function makeSquare() {
  const square = document.createElement('div');
  const squareWrapper = document.querySelector('.square-wrapper');
  square.classList.add('square');
  squareWrapper.appendChild(square)
}

function changeSquareColorToPink() {
    const square = document.querySelector('.square:nth-child(1)');
  square.style.setProperty('--square-color', 'pink');
}

function changeSquareDefaultColorToBlue() {
    const squareWrapper = document.querySelector('.square-wrapper');
  squareWrapper.style.setProperty('--square-color', 'blue');
}

window.addEventListener('load', setup)
.bt_makeSquare {
  margin-top: 6em;
}
.square-wrapper {
  --square-color: red;
  --square-size: 50px;
  margin-top: 2em;
}
.square {
  margin: 1em;
  display: inline-block;
  width: var(--square-size);
  height: var(--square-size);
  box-sizing: border-box;
  border: 1px solid var(--square-color);
  background-color: var(--square-color);
}
<button class="bt_makeSquare" onclick="makeSquare()">Make a square</button>
<div class="square-wrapper"></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...