我正在尝试在页面顶部创建一个固定的页眉。因此,当用户向下滚动时,标题会保持在顶部。然而,这只是Chrome、FireFox和Opera中流畅滚动的作品。
如果你看过下面的代码。使用IE和Google Chrome打开。你会看到不同的!标头必须保留在包装中。
示例代码
我想知道当设置为绝对值时,如何在div元素内重新定位对象时使滚动平滑,以使其保持在框的顶部。
HTML:
<div id="wrapper">
<header>
<h2>Title Header</h2>
</header>
Content page
</div>
CSS:
#wrapper{
height:200px;
overflow-y:scroll;
position:relative;
}
#wrapper > p {
position: absolute;
z-index: 0;
}
#wrapper header {
background-color:#ccc;
position: absolute;
z-index: 10;
display: block;
top: 0px;
padding:10px;
width: 100%;
}
#wrapper header h2 { margin:0 }
Javascript:
$(function(){
$('#wrapper').scroll(function(e){
$('header').css('top',parseInt($('#wrapper').scrollTop())+'px');
});
});
为了跨浏览器兼容性,我宁愿使用这个CSS并删除JS:
// same CSS...
#wrapper p {
margin-top: 50px; //no positioning just a top margin
z-index: 0;
}
#wrapper header {
background-color:#ccc;
position: fixed; // from absolute to fixed
z-index: 10;
display: block;
top: 0px;
padding:10px;
width: 100%;
}
//same CSS...
演示。