Javascript 具有动态标题大小的Div和带有滚动条的内容
我正在尝试创建一个具有固定高度的容器div,其中包含两个div,一个header div和一个content div。header可以动态增长,我希望content div占据剩余的空间。容器div不应超过指定的大小,如果内容增长过多,则contentdiv应滚动 我的当前代码如下,但不起作用:Javascript 具有动态标题大小的Div和带有滚动条的内容,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正在尝试创建一个具有固定高度的容器div,其中包含两个div,一个header div和一个content div。header可以动态增长,我希望content div占据剩余的空间。容器div不应超过指定的大小,如果内容增长过多,则contentdiv应滚动 我的当前代码如下,但不起作用: <div id="container"> <div id="header"> <button id="btnHeader" type="button"
<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;
}
增加标题我的标题
增加我的内容
#容器{
高度:300px;
宽度:400px;
最大高度:300px;
背景颜色:灰色;
}
#标题{
宽度:100%;
高度:自动;
背景颜色:蓝色;
}
#内容{
宽度:100%;
身高:100%;
溢出y:滚动;
背景色:红色;
}
示例如下:
发生的情况是,content div始终保持相同的大小,从而使container div增长。有什么想法吗
我用container div上的
overflow:hidden
更新了fiddle,使其大小保持不变。内容增加会将滚动条添加到内容div,标题增加会向下推内容div。如果我正确理解了您的要求,这就是您要找的吗?我对答案做了修改,但我也会尝试解释
对于这种级别的动态大小调整,您必须使用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();
});
希望有帮助 如果内容增长,则内容应滚动。但是如果标题变大,内容是否应该缩短?还是应该滚动容器?如果标题比容器长怎么办?是的,如果标题变长,内容应该缩短。关于标题比容器长,我们可以假设这永远不会发生。硬要求是容器保持其大小,并且内容是唯一滚动的内容。谢谢您需要flexbox或javascript来实现这一点