当前位置: 首页>前端>正文

css 子容器高度超出父容器最小高度 div适应父容器高度

一、DIV最小高度且自适应高度

    经常使用div布局的盆友应该有过这样的经验,并且这样的情况并不少见:有一个div,当它里面的内容超过它的高度时,让这个div的高度随内容自动变化(自适应),但是如果内容很少时,又想让这个div的高度保持一个固定的最小值。

    我们知道,在IE6中,如果子容器的高度超过父容器的时候,父容器会被子容器撑开,所以我们可以直接设置一个height的高度值即可。但是在IE7+FirefoxChrome中就不行了,它不会自动撑开。如果要设置div自适应高度,我们可以采用height:auto;这个属性;不过这个属性IE6又不支持了。现在,我们假设这个div的默认高度是100px,对于这种情况,我们可以使用:

.myDiv{
    height:auto!important;
    height:100px;
    min-height:100px;
}

注释:因为IE6识别不了!importantauto对它也不管用,因此会应用了后面的height:100px的样式;而在IE7+、Firefox、Opera、Chrome中,这个!important 关健字在 CSS 中的优先性是大于后面的 height:240px 的,因此它的渲染结果中只接受了 height:auto !important min-height:240px

 

二、iframe自适应高度

    iframe标签虽然已经被舍弃,但在很多情况下我们迫不得已而用之,而随之而来的iframe的高度问题就不可避免了。

同域、子页面高度不会动态增加

    这种情况最简单,直接通过脚本获取子页面实际高度,修改iframe元素高度即可。但有两点必须注意:

    a,如果子页面内有绝对定位或没有清除浮动的元素,不同浏览器得到的document.documentElement.scrollHeightdocument.body.scrollHeight结果不相同,所以要么进行浏览器检测,要么用Math.max计算它们的最大值.

    b,iframe包含页面可能非常大,需要很长的加载时间,为此直接计算高度的时候,很可能页面还没下载完,高度计算就会有问题。所以最好在iframeonload事件中计算高度。

<iframe id="frame_content" src="iframe_b.html" scrolling="no" frameborder="0" onload="reinitIframe();" />
<script type="text/javascript">

function reinitIframe(){
    var iframe = document.getElementById("frame_content");

    var bodyHeight = iframe.contentWindow.document.body.scrollHeight;
    var docHeight = iframe.contentWindow.documnet.documentElement.scrollHeight;
        
    iframe.height = Math.max(bodyHeight, docHeight);    
}
</script>

②同域、子页面高度会动态增加

    原理与第一种情况一样,多一个计时器,一直检测字页面高度,当子页面高度和iframe的高度不一致时,重新设置iframe的高度。这边也可以加一个try在js出错时,加一个足够的高度。

    当iframe窗体高度高于文档实际高度的时候,高度取的是窗体高度,而当窗体高度低于实际文档高度时,取的是文档实际高度。因此,要想办法在同步高度之前把高度设置到一个比实际文档低的值。所以,在iframe的添加 height="100″,让页面加载的时候先缩到足够矮,然后再同步到一样的高度。

<iframe id="frame_content" height="100" src="iframe_b.html" scrolling="no" frameborder="0" />
<script type="text/javascript">
 
function reinitIframe(){
    var iframe = document.getElementById("frame_content");
    try{
        var bodyHeight = iframe.contentWindow.document.body.scrollHeight;
        var docHeight = iframe.contentWindow.documnet.documentElement.scrollHeight;
         
        iframe.height = Math.max(bodyHeight, docHeight);
    } catch(ex){
        iframe.height  = 1800;
    }   
}
 
window.setInterval("reinitIframe()",200);
</script>

  


https://www.xamrdz.com/web/25d1928864.html

相关文章: