在使用 DIV 和 CSS 進行網頁布局時,div 的自適應高度與寬度是很常見的問題。為了保證頁面的整體美觀,我們往往需要讓兩個或多個層的高度保持一致。以下介紹兩種常見的自適應實現方法。
<div style="width:300px;">
<div id="Left" style="float:left;background-color:blue;">1<br/>3<br/>5<br/></div>
<div id="Right" style="float:right;background-color:red;">2</div>
</div>
<script type="text/javascript" src="https://jt.875.cn/js/jquery.js"></script>
<script type="text/javascript">
$(function(){
var heightLeft = $("#Left").height();
var heightRight = $("#Right").height();
if (heightLeft > heightRight)
{
$("#Right").height(heightLeft);
}
else
{
$("#Left").height(heightRight);
}
})
</script>
原理很直觀:分別取得左右兩欄的高度,比較後將較矮的一欄調整到與較高的一欄相同,從而實現等高效果。
<div id="top" style="height:200px;"></div>
<div id="box">dsafsafsafsafsafdsa</div>
<script>
window.onload = function (){
function auto_height()
{
document.getElementById("box").style.height =
document.documentElement.clientHeight - 200 + "px";
}
auto_height();
onresize = auto_height;
}
</script>
這段代碼透過取得瀏覽器視窗的高度,減去頂部固定高度後,動態設定內容區的高度,並透過 onresize 事件在視窗縮放時即時調整,讓內容區始終填滿剩餘空間。