基于窗口大小的可滚动div上的动态最大高度

时间:2013-12-14 11:34:03

标签: html css twitter-bootstrap-3

尝试实现具有自动最大高度的div,以便当div中的列表非常长时,它不会强制整个页面滚动,而是将其高度扩展到尽可能低的范围而不进行制作页面滚动,并在div本身内有一个滚动条。目前,它的最大高度为800px。这应该是自动设置,具体取决于浏览器视口分辨率。

http://plnkr.co/edit/vt2tvVAErdpmPRkg1txd?p=preview

<body>
<div class="container">
<div class="row">
    <div class="col-md-8">
 <div class="panel panel-body panel-primary">
 MainContent
 </div>
   </div> <!-- /.col-md-8 -->
    <div class="col-md-4">
            <div data-spy="affix">
           some list here
            <div style="max-height:800px;
overflow-y: auto; overflow-x: hidden; margin-top: 5px">
                <div class="panel panel-body panel-default">


                         another list here, but this div should have an auto max height so that when the list is really long, it does not force the entire page to scroll, but instead extends its height to as far low as it can without making the page scroll, and have a scrollbar within the div itself. Currently, it is set with max-height of 800px. This should be autoset depending in browser viewport size. 
                    </br>

                    </br>

                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
</body>

2 个答案:

答案 0 :(得分:1)

好的,所以在你的plnkr中,我看不到你的bootstrap col-md-x类应用于DIV(我不知道为什么?)。 但无论如何,你想把你的词缀保留在页面的右侧,有4列宽。那么,在这种情况下你应该检查加载时的浏览器高度并调整浏览器的事件大小,然后相应地设置max-height。此最大高度不应包含DIV.affix的边距。

好吧,代码应该是:

function setMaxheight(){
    var affixEle = $(">div", ".affix").first(),
        winHeight = $(window).height();

    // If there is some margins from top or bottom, remove it like:
    // winheight -= 20;

    affixEle.css({
        'max-height' : winHeight + "px"
    });
}

$(function(){
    setMaxheight();

    $(window).resize(function(){
        setMaxheight();
    });
});

CSS应该是:

.affix > div{
    margin-top: 5px;
    overflow: auto; /*You dont need to put overflow-y or something. overflow:auto works perfectly*/
}

答案 1 :(得分:0)

试试这个:

jquery:

   var divHeight=$(window).height()*62/100; 
   $("divid").css("max-height",divHeight);

javascript:

   var w = window.innerWidth;
   w=w*62/100;
   document.getElementById("p1").style.maxHeight=w+"px";