0

我有这个可以滚动内容的容器。我希望这个容器中的标题始终保持在顶部。

http://jsfiddle.net/z9ze5/

容器:

.lists {
    width: 300px;
    height: 250px;  
    margin: 30px auto;
    background: #39C;
    overflow: scroll;
    position: relative;
}

标题:

.box_header {
    width: 100%;
    height:30px;
    overflow:hidden;
    position: absolute;
    margin: 0;
    background: #DDD;
    z-index: 999;
}
4

4 回答 4

2

如果您想要非 css 修复,请添加此侦听器...

$('.lists').scroll(function() {
    $('.box_header', this).css('top', $(this).scrollTop()+'px');
});

然后更改 .lists css 以提供相对定位

.box_header {
    width: 100%;
    height:30px;
    overflow:hidden;
    position: relative;
    margin: 0;
    background: #DDD;
    z-index: 999;
}
于 2013-03-13T15:15:14.340 回答
2

如果您愿意更改标记,这是一种方法:

<div class="lists">
    <header class="box_header">
        <h1>HEADER 2</h1>
        <div class="setting" id="btn2"></div>
    </header>
    <section class="content">
        <p>Lorem Ipsum ....</p>
    </section>
</div>

将滚动区域包裹在<section>(或其他块级元素)中。

对于您的 CSS:

.lists {
width: 300px;
height: 250px;
margin: 30px auto;
background: #39C;
position: relative;
}
section.content {
width: 300px;
height: 220px;
margin: 0 auto;
background: #39C;
position: relative;
top: 30px;
overflow: scroll;
}

请看小提琴:http: //jsfiddle.net/audetwebdesign/nGGXx/

更高级的例子

如果您研究以下示例:

http://jsfiddle.net/audetwebdesign/fBNTP/

你可以看到你的滚动框可以如何应用在一个半灵活的布局中。我将两个滚动框并排排列,并使其宽度与页面宽度成比例。

高度更难调整。我固定了父容器的高度,见以下规则:

.contentWrapper {
    border: 1px solid red;
    margin-top: 1.00em;
    padding: 30px 0;
    overflow: auto;
    height: 400px;
}

如果将高度从 400px 更改为其他值,滚动框将自行调整。

希望这些示例能让您和其他人对如何构建这些更高级的布局设计有更多的了解。

于 2013-03-13T15:16:07.137 回答
0

相对位置中的任何绝对位置对于相对容器都是绝对的。为了使标题保持原位,您需要将其放置在滚动容器上方而不是内部。

于 2013-03-13T15:02:49.043 回答
0

查看添加位置:固定到您的标题 div .box_header。您可能必须将框标题 div 的高度的填充添加到 section.content ,但因为您将其设置为 30px 应该没问题。IE6 及更低版本存在固定定位问题,但希望我们现在可以忍受 - 使用它的人比仍在听 Moby 的人少。

于 2013-03-13T23:28:52.960 回答