制作一个按钮来创建盒子

时间:2018-10-14 01:17:09

标签: javascript html css

每当用户单击按钮时,我都必须在div(这里的divbox)内创建框。到目前为止,我已完成以下操作,但未创建任何框。

代码:

<!DOCTYPE html>
<html>
    <head>
        <style>
      .myDiv {
        height: 50px;
        width: 50px;
        border-color: blue;
          }
      #box {
        width: 700px;
        height: 700px;
        border: solid black;
      }
    </style>
    </head>
    <body>
        <h1>The onclick Event</h1>
        <button id ="theBoxes" >Creating boxes</button>
        <div id = "box"></div>
        <script>
        var x = document.getElementById("theBoxes");
        x.addEventListener("click", myFunction)
          function myFunction() {
            var box = document.createElement('div');
            box.classList.add('myDiv');
            document.body.appendChild(box); 
          }
          </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

var x = document.getElementById("theBoxes");
x.addEventListener("click", myFunction)
function myFunction() {
  var box = document.createElement('div');
  box.classList.add('myDiv');
  document.body.appendChild(box); 
}
.myDiv {
  height: 50px;
  width: 50px;
  border: 1px solid blue;
}
#box {
  width: 700px;
  height: 700px;
  border: solid black;
  position: absolute;
}
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <h1>The onclick Event</h1>
        <button id ="theBoxes" >Creating boxes</button>
        <div id = "box"></div>
    </body>
</html>

您的代码正在运行,很遗憾,border-color: blue中的myDiv无法正常工作,并且该框也已添加到div #box之外。

因此,我通过在position: absolute中添加#box和在border: 1px solid blue中添加.myDiv来修改您的代码。

相关问题