使元素的上边距始终与另一个

时间:2017-01-22 15:13:30

标签: javascript css

我有一个固定的标题,这意味着内容会在它下面丢失,除非我给它一个等于标题高度的上边距。这一点很好,直到标题更改大小(由于浏览器窗口的大小更改)。

目前我在窗口调整大小时有一个eventListener,它获取头部的计算高度并将其应用于内容的style.marginTop。这个问题是我需要它在页面加载时发生,而不仅仅是窗口调整大小,并且当我更改浏览器窗口的大小时,对标题高度做出如此多的请求似乎是不好的做法。

有人有更好的主意吗?谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

有三种方法可以解决这个问题;

1)继续使用您所使用的方法,但在页面加载/就绪时触发resize事件(将调整大小逻辑保持在原位)。这不是一个可怕的想法,主要是因为用户不会经常调整窗口大小。

3)重新处理标题,以便在内容需要换行时,它可以作为弹出/滑动菜单使用。 (最佳UI推荐)

2)强制标题内容不包装(white-space:nowrap)并让用户垂直滚动(不推荐)

我个人会选择#2,移动/平板电脑设计最好在用户需要之前将其排除在外。

答案 1 :(得分:0)

headercheck();
window.addEventListener('resize',headercheck);
function headercheck(){

var headerheight=document.getElementById("header").offsetHeight;
//console.log(headerheight);gives height of header
document.getElementById("content").style.top=headerheight+"px";
}
#header{background:#676767;
padding:20px;
box-sizing:border-box;
position:fixed;
width:100%;}
#content{
position:relative;

  }
<div id="header">
this is the header 
</div>
<div id ="content">
content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content
</div>

希望有所帮助