由于设计页面需要,要把两个并排显示的 div 实现一样高的效果, n 行 n 列布局,每列高度(事先并不能确定哪列的高度)相同,每个设计师追求的目标。方法有以下几种: 1 JS 实现(判断 2 个 d

来源:互联网 发布:土耳其历史 知乎 编辑:程序博客网 时间:2024/06/12 21:14

由于设计页面需要,要把两个并排显示的 div 实现一样高的效果, n 行 n 列布局,每列高度(事先并不能确定哪列的高度)相同,每个设计师追求的目标。方法有以下几种: 1 JS 实现(判断 2 个 div 高) 2 纯 css 方法; 3 加背景图片实现。首先说下本博客实现的 2 个 div 一样高的方法(即 js 方法)
    div+css 基本布局:
<div id="mm">
<div id="mm1"></div>
<div id="mm2"></div>
</div>
     1 js 实现 div 自适应高度
 代码如下:
<script type="text/javascript">
<!--
window.onload=window.onresize=funct {
if document.getElementByIdx_x "mm2" .clientHeight<document.getElementByIdx_x "mm1" .clientHeight {
document.getElementByIdx_x "mm2" .style.height=document.getElementByIdx_x "mm1" .offsetHeight+"px";
}
else{
document.getElementByIdx_x "mm1" .style.height=document.getElementByIdx_x "mm2" .offsetHeight+"px";
}
}
-->
</script>
 
     注:网上公布了不少方法,但代码或多或少有错;上面的无错代码;测试在 IE6.0/IE7.0 下通过,考虑绝大数人仍然用的 IE 所以并没有在 opera 和 firefox 下调试,哪位用的 opera 或 ff 可以协助看看 飘易博客 DIV 否保持了一致的高度。
 
    2 纯 CSS 方法
 
    css 里代码(调试通过,但不会显示 div 下边框,即 border-bottom
 

#m1,#m2
{
padding-bottom: 32767px !important;
margin-bottom: -32767px !important;
}
@media all and  min-width: 0px  {
#m1,#m2
{
padding-bottom: 0 !important;
margin-bottom: 0 !important;
}
#m1:before, #m2:before
{
content: '[DO NOT LEAVE IT IS NOT REAL]';
display: block;
background: inherit;
padding-top: 32767px !important;
margin-bottom: -32767px !important;
height: 0;
}
}

 

    3 加背景图片
 
     这个方法,很多大网站在使用,如 163 sina 等。
 
    XHTML 代码:
 
<div id="wrap">
<div id="column1"> 这是第一列 </div>
<div id="column1"> 这是第二列 </div>
<div class="clear"></div>
</div>
 
    CSS 代码 :
 
#wrap{ width:776px; background:url bg.gif  repeat-y 300px;}
#column1{ float:left; width:300px;}
#column2{ float:right; width:476px;}
.clear{ clear:both;}
 
     还有其他一些方法,但主流就是这几种了如果你还有关于多个 div 自适应高度的好的代码。
4、附上一段采用jquery脚本来控制两个对象高度一致的代码

<script type="text/javascript" src="../js/jquery1.4.2.js">
</script>
<script language="javascript">
$(document).ready(function(){
 AdjustColumnsHeight(".content",".bar");
});
 
AdjustColumnsHeight = function(obj1,obj2)
{
 var h1 = $(obj1).outerHeight();
 var h2 = $(obj2).outerHeight();
 var mh = Math.max( h1, h2);
 $(obj1).height(mh);
 $(obj2).height(mh);
}
</script>

0 0
原创粉丝点击