如何在HTML中插入重复的元素,只用Javascript DOM?

问题描述 投票:0回答:1

enter image description here> 我有一个黄色的盒子(class="yellow-box"),和一个蓝色的小盒子。

框(class="box-1")。我需要用JavascriptDOM在HTML中输入12次相同的div--而不需要在HTML中硬编码。

HTML代码

<html>
        <head>
            <title>Match the box</title>

            <link rel="stylesheet" type="text/css" href="style.css">
            <script src="boxGame.js"></script>
        </head>
        <body class="background-img">
            <div class="yellow-box">
              <div class="box-1"> </div>


            </div>

        </body>
    </html>



 .background-img {
    background-image: url("fundal.jpeg");
    background-repeat: no-repeat;
    background-size: cover;
}

.yellow-box {
    background-color: yellow;
   width: 850px;
   height: 600px;
   margin: auto;
   top: 30px;
   position: relative;

}

.box-1 {
    background-color: blue;
   width: 160px;
   height: 120px;
   float: left;
   position: relative;
   margin: 25px;
  }
javascript html dom
1个回答
2
投票

将这段代码添加到你的javascript文件中,或者添加到你的脚本标签中。

let outerDiv = document.querySelector('.yellow-box');

for(let i = 0; i++; i<=12 ){
    let boxDiv = document.createElement('div');
    div.setAttribute('class', 'box-1');

    outerDiv.appendChild(boxDiv);
}
© www.soinside.com 2019 - 2024. All rights reserved.