简体   繁体   中英

Make a button to create boxes

I have to create boxes inside of a div (The div here is box ) whenever the user clicks the button. I have done the following so far, but no boxes are created.

Code:

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

 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>

Your code is working, unfortunately border-color: blue in myDiv doesn't work and the box also added outside your div #box .

So I modify a bit your code by adding position: absolute in #box and border: 1px solid blue in .myDiv .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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