2016-01-21 48 views
1

如何在html頁面上重複X次div, 可以說我想設置變量來聲明重複次數。 重複此部分5次,我認爲它是與JS。重複一次div的次數

<div class="blackstrip">black</div> 
<div class="bluestrip"> 
    BLUE 
    <div class="whitestrip">WHITE strip</div> 
</div> 

我加入的CSS,因爲它出來奇怪的表情 -

.blackstrip{ 
opacity: 0.8; 
width: 600px; 
height: 100px; 
background-color: black; 
background-position: center; 
padding-top: 10px; 
padding-bottom: 10px; 
text-align: center; 
margin: 0 auto; 

}

.bluestrip{ 
opacity: 0.5; 
width: 600px; 
height: 300px; 
background-color: blue; 
background-repeat: none; 
padding-bottom: 10px; 
position: relative; 
margin-top:50px; 
margin: 20px auto; 

}

.whitestrip{ 
opacity: 0.8; 
width: 100px; 
height:300px; 
background-color: gray; 
position: relative; 
float: right; 
padding-top: 10px; 
padding-bottom: 10px; 
} 
+0

在循環中使用模板語言。 – 2016-01-21 11:38:13

回答

3

只需使用一個for循環如:

var amount = 5; 
for (var i = 0; i < amount; i++){ 
    var new_div = document.createElement("div"); 
    new_div.className = "bluestrip"; 
    document.body.appendChild(new_div); 
    console.log("This is repeat " + i); 
} 

簡單的技術,是吧?

https://jsfiddle.net/d15e9r6z/

像安德烈亞斯說,如果你使用 DocumentFragment更改多個DOM的更有效。

+0

使用[''DocumentFragement'](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment),所以你只需要改變一次DOM而不是'amount'次 – Andreas

+0

添加這個爲選項。謝謝。 – Maurize

+0

@Maurice好的,但它並不完全。當你嘗試重複3個div時,它顯示不好。你怎麼加入new_div.className = 3的divs – eyalix