同时,也有网友提问到“如果右块高度比左块低,会不会导致左块的内容被溢出不显示之类的问题。应该是取左右2者的最高值吧来对齐吧”。
的确应该是哪个div Height值大,就将其值赋给Height值小的div,从而使2个div高度始终保持一致。看代码:
代码如下 |
复制代码 |
function $(id){ return document.getElementById(id) } function getHeight() { if ($(“left”).offsetHeight>=$(“right”).offsetHeight){ $(“right”).style.height=$(“left”).offsetHeight + “px”; } else{ $(“left”).style.height=$(“right”).offsetHeight + “px”; } } window.onload = function() { getHeight(); }
|
经测试,该代码有效。
另外,在实际运用,可能还会存在由于左div或右div存在padding属性而导致上述取值变多或变少的问题。比如,最终赋值时发现left比right还高10px,那么也可以通过修改上述代码解决:
代码如下 |
复制代码 |
$(“left”).style.height=$(“right”).offsetHeight-10 + “px”;
|
实例
代码如下 |
复制代码 |
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml”> <head> <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ /> <title>左右div自适应同等高度</title>
<style type=”text/”> #left{background:#999999; float:left; width:100px;} #right{background:#0066FF; color:#fff; width:300px; float:left; } .clear{clear:both;} </style>
</head>
<body> <h3>1. 右边div内容高度高于左边div</h3> <div id=”left”> 14万公里收费10万在中国 </div>
<div id=”right”> ccfsfdsfsdf
</div>
<script type=”text/” src=”jquery-1.5.1.min.js”></script> <script type=”text/javascript”> function $(id){ return document.getElementById(id) } function getHeight() { if ($(“left”).offsetHeight>=$(“right”).offsetHeight){ $(“right”).style.height=$(“left”).offsetHeight + “px”; } else{ $(“left”).style.height=$(“right”).offsetHeight + “px”; } } window.onload = function() { getHeight(); } </script> </body> </html>
|