简体   繁体   English

获取top div的高度,并将该值作为另一个DIV的顶部填充

[英]Get the height of top div and place that value as a top padding of another DIV

I am using header div as a fixed header but the height of that div will change on regular basis because the matter comes dynamically. 我将头div用作固定头,但是该div的高度会定期更改,因为问题是动态发生的。 Now the next div which is just below to it was shown when padding top is given to that div. 现在,当给该div填充padding top时,显示了下一个div。

so that the content DIV will also change its position as the height of the header div changes. 因此,随着标题div的高度更改,内容DIV也将更改其位置。

I will be greatful if any one can give the code. 如果有人可以给出代码,我将不胜感激。

This would be the jQuery answer I think. 这就是我认为的jQuery答案。 More detail would be helpful though. 不过,更多细节会有所帮助。

$("#header").resize(function() {
  $("#otherdiv").css("padding", somevalue);
});

I would advice (if possible) to create a parent div that contains both the header div and the content div. 我建议(如果可能)创建一个包含标题div和内容div的父div。 Optionally, on either div set as css-style clear: both; (可选)在设置为css样式的任一div上clear: both; . This way the vertical position of the content div will be relative to the header div. 这样,内容div的垂直位置将相对于标头div。

<div id="parent">
    <div id="header" style="clear: both"></div>
    <div id="content"></div>
</div>

Two things I can think of, as I was contemplating this same issue recently: 我最近在考虑同一问题时,可以想到两件事:

I think the most direct answer you're looking for is {element}.offsetHeight. 我认为您要寻找的最直接答案是{element} .offsetHeight。 From what I played with in FireFox (unsure about other browsers) this seems to be the height of the element. 从我在FireFox中玩过的(不确定其他浏览器)来看,这似乎是元素的高度。 You might include a few pixels to this when placing your other div to allow the spacing you want. 放置另一个div时,您可能会为此添加一些像素,以允许所需的间距。

However, if you place the divs one after another (siblings) and they're not set as floating, changing the upper div should move the lower div as its contents change. 但是,如果您将div接一个(兄弟姐妹)放置,并且它们未设置为浮动,则更改上div会随着内容的变化而移动下div。

for the html of TheStijns answer (with header css set to position:absolute) you can use following code: 对于TheStijns答案的html(标头css设置为position:absolute),可以使用以下代码:

window.setInterval(function(){
  var header = document.getElementById('header');
  var content = document.getElementById('content');
  content.style.paddingTop = header.offsetHeight + 'px';
}, 100);

the event driven jquery solution makes more sense though. 事件驱动的jQuery解决方案更有意义。

for the simple case you described it shouldn't be necessary though to use javascript. 对于您描述的简单情况,虽然没有必要使用javascript。 html with a bit of css should work. 带有一点CSS的html应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM