Div采用动态标题大小,内容采用滚动条

Div with dynamic header size and content with scroll bar

本文关键字:滚动条 动态 标题 Div      更新时间:2023-09-26

我正在尝试创建一个具有固定高度的容器div,其中有两个div,一个标头div和一个内容div。标头可以动态增长,我希望内容div占据其余空间。容器div不应超过指定的大小,如果内容增长到很大,则内容div应滚动。

我当前的代码如下,但不起作用:

<div id="container">
   <div id="header">
        <button id="btnHeader" type="button">Increase Header</button>MY HEADER</div>
<div id="content">
    <button id="btnContent" type="button">Increase Content</button>MY CONTENT</div>
</div>
#container {
     height: 300px;
     width: 400px;
     max-height: 300px;
     background-color: grey; 
}
#header {
     width: 100%;
     height: auto;
     background-color: blue;
}
#content {
     width: 100%;
     height: 100%;
     overflow-y: scroll;
     background-color: red;
}

此处的示例:http://jsfiddle.net/ep1qab0v/

所发生的情况是,内容div始终保持相同的大小,从而使容器div增长。有什么想法吗?

http://jsfiddle.net/ep1qab0v/3/,

我已经在容器分区上用overflow:hidden更新了fiddle,这使它保持了相同的大小。内容的增加将滚动条添加到内容div中,而标题的增加则将内容div向下推。如果我正确理解了你的要求,这就是你想要的?

我对答案做了一些修改,但我也会尽力解释。jsfiddle示例

对于这种级别的动态调整,您必须使用javascript。由于内容是可滚动的,而标题不是,因此每次标题大小更改时都必须创建一个调用的对象或函数。通过这种方式,您可以根据主容器测试标头的高度,并根据需要更改内容框。

我创建了一个简单的对象,当页面加载时,您可以使用它来初始化框。此外,您可以在每次调整页面大小或更改页眉大小时调用。

var sizing = {
    height: null,
    header: null,
    content: null,
    //Initializes whatever you need
    //just cacheing the header and content
    //and setting the height restriction
    init: function(){
        //Set the height of the users window
        //you can change this to whatever you want
        //but this is dynamic to the browser window
        this.height = window.innerHeight ? window.innerHeight : $(window).height();
        //Set header and content elements
        //for later use
        this.header = $('#header');
        this.content = $('#content');
        this.resize();
    },
    //Ressize the boxes to fit
    //this needs to be called after
    //  every change to the header
    resize: function(){
        this.content.css({
            height: (this.height - this.header.height()) + "px"
        });
    }
};

当页面加载时,您需要调用.init()来初始化对象

$(document).ready(function(){
    //Whatever you need to do
    //Initialize the sizing
    sizing.init();
});

然后你可以从内部事件称之为

$('body').on('click', '#some-element', function(e){
    //Do some stuff
    //Then resize the divs
    sizing.resize();
});

希望能有所帮助!