可变高度的粘性标题

时间:2011-08-19 11:54:44

标签: javascript jquery html css

因此,即使用户向下滚动,我也需要一个始终显示在视口顶部的标题。这一点相当容易,使用类似的东西:

body {
    padding-top: 100px; /* height of the header */
}

#header {
    position: fixed;
    top: 0;
    left: 50%;
    margin-left: -500px; /* Half the width of the header */
    width: 1000px;
    height: 100px;
}

但是,现在我的问题是我并不总是知道标题的高度,因为客户希望顶部横幅广告也跟随,但可能并不总是存在

因此,有时标题可能如下所示:

<div id="header">
    <img src="#" class="top_banner" />
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

有时看起来像这样:

<div id="header">
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

好消息是横幅广告总是具有相同的尺寸。所以基本上#header可能是没有横幅的100px,如果有横幅就是250px。

我的问题是:有没有一个很好的CSS方法来解决这个问题?如果没有,我怎么能用Javascript解决它?

4 个答案:

答案 0 :(得分:4)

$(document).ready(function(){
 $('body').css('padding-top', $('#header').height() + 'px');
});

这可以帮到你

答案 1 :(得分:1)

(懒惰回答)

更改#header div的className,具体取决于它是否有图像。

CSS

body {
    padding-top: 100px; /* height of the header */
}

.header_no_image, .header_with_image {
    position: fixed;
    top: 0;
    left: 50%;
    margin-left: -500px; /* Half the width of the header */
    width: 1000px;
}

.header_no_image {
  height: 100px;
}
.header_with_image {
  height: 250px;
}

带图片

<div id="header" class="header_with_image">
    <img src="#" class="top_banner" />
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

没有图片

<div id="header" class="header_no_image">
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

可能有更好的解决方案,但这可行...

答案 2 :(得分:0)

不确定CSS,但是这个javascript应该为你做基本的工作:

document.body.style.paddingTop = document.getElementById('header').offsetHeight + 'px';

答案 3 :(得分:0)

我编写了一个jquery插件来解决这类问题:https://github.com/ArthurClemens/jquery-sticky-plugin

检查这是否适合您。

相关问题