2016-01-18 104 views
2

我有一個DIV元素,裏面還有一個DIV作爲我體內網站的最後一個元素。我想將它的高度伸展到100%並給它一些背景顏色(到目前爲止效果很好),但是我在網站上有一個按鈕,它向內部DIV添加了一個表格。用javascript添加元素到DIV(高度100%)不會改變div的高度?

問題:當我不停地添加一些這些表格時,它們會從div-div的彩色背景中溢出,並不會隨其內容拉伸(下面的小提琴演示了我的問題,只需點擊幾下進行操作即可看到文字走出藍色區域,但藍色區域不再延伸)。

有沒有辦法如何做到這一點?

非常感謝。

HTML代碼

<div id="button"> 
proceed 
</div> 
<div id="box"> 
    <div id="results"> 
    </div> 
</div> 

CSS代碼

html, body { 
    height: 100%; 
} 

#box { 
    width: 100%; 
    height: 100%; 
    background-color: #3498eb; 
} 

#clearDiv { 
    clear: both; 
} 

Javascript代碼

var button = document.getElementById('button'); 
button.addEventListener('click', function(event) { 
    var results = document.getElementById('results'); 

    for (var i = 0; i < 10; i++) 
    { 
    var table = document.createElement('table'); 
    var row = document.createElement('tr'); 
    var cell1 = document.createElement('td'); 
    var cell2 = document.createElement('td'); 
    results.appendChild(table); 
    table.appendChild(row); 
    row.appendChild(cell1); 
    row.appendChild(cell2); 
    cell1.innerHTML = 'test1'; 
    cell2.innerHTML = 'test2'; 
    } 

    console.log('done'); 
}, false); 

fiddle here

回答

2

使用min-height,而不是heightheight告訴元素停留在特定的高度。另一方面,min-height設置元素的最小高度,並允許它在需要時展開。

#box { 
    width: 100%; 
    min-height: 100%; 
    background-color: #3498eb; 
} 

演示

var button = document.getElementById('button'); 
 
button.addEventListener('click', function(event) { 
 
\t var results = document.getElementById('results'); 
 
\t 
 
    for (var i = 0; i < 10; i++) 
 
    { 
 
    var table = document.createElement('table'); 
 
    var row = document.createElement('tr'); 
 
    var cell1 = document.createElement('td'); 
 
    var cell2 = document.createElement('td'); 
 
    results.appendChild(table); 
 
    table.appendChild(row); 
 
    row.appendChild(cell1); 
 
    row.appendChild(cell2); 
 
    cell1.innerHTML = 'test1'; 
 
    cell2.innerHTML = 'test2'; 
 
    } 
 

 
    console.log('done'); 
 
}, false);
html, body { 
 
    height: 100%; 
 
} 
 

 
#box { 
 
    width: 100%; 
 
    min-height: 100%; 
 
    background-color: #3498eb; 
 
} 
 

 
#clearDiv { 
 
    clear: both; 
 
}
<div id="button"> 
 
proceed 
 
</div> 
 
<div id="box"> 
 
    <div id="results"> 
 
    </div> 
 
</div>

0

應該能夠簡單地改變:

#box { 
    width: 100%; 
    min-height: 100%; 
    background-color: #3498eb; 
} 
+0

'溢出y'是** **不規範與流行的看法相反。因爲這個原因,Firefox也不支持它。 –

1

更改CSS:

html, 
body { 
    height: 100vh; 
} 
#box { 
    position: relative; 
    min-width: 100%; 
    min-height: 100%; 
    background-color: #3498eb; 
    overflow: auto; 
} 
#results { 
    position: absolute; 
    top: 0; 
    left: 0; 
} 

https://jsfiddle.net/zer00ne/mw1w4ykb/