当页面有足够的内容需要向下滚动时,页眉和菜单将消失。现在,页眉不是问题,但我真的很希望菜单固定在页面顶部,同时仍向下滚动内容。
我在这里发布带有该页眉和菜单的页面代码
<html>
<head>
<noscript><meta http-equiv="REFRESH" content="0;URL=error-no-javascript.html"></noscript>
<link rel="shortcut icon" href="http://www.vtsim.com/favicon.png" />
<title>TRAINZ - VTsim.com</title>
</head>
<body ondragstart="return false" onselectstart="return false" oncontextmenu="return false" link="red" alink="red" vlink="red">
<font face="Arial" size="2" color="black">
<p align="center">
<img src="http://www.vtsim.com/image/head_trz_1.png"><a href="http://fs.vtsim.com" border="0"><img src="http://www.vtsim.com/image/head_trz_2.png"></a>
</p>
//--- now starts the menu wich I pretend to be kept fixed on top when scrolling
<p align="center">
<a href="http://trainz.vtsim.com" border="0"><img src="http://www.vtsim.com/image/b_home_a.png"></a><a href="http://trainz.vtsim.com/trains.htm" border="0"><img src="http://www.vtsim.com/image/b_trz_trains_i.png"></a><a href="http://trainz.vtsim.com/tracks.htm" border="0"><img src="http://www.vtsim.com/image/b_trz_tracks_i.png"></a><a href="http://trainz.vtsim.com/trackside.htm" border="0"><img src="http://www.vtsim.com/image/b_trz_trkside_i.png"></a><a href="http://trainz.vtsim.com/scenery.htm" border="0"><img src="http://www.vtsim.com/image/b_trz_scenery_i.png"></a><a href="http://trainz.vtsim.com/routes.htm" border="0"><img src="http://www.vtsim.com/image/b_trz_routes_i.png"></a><a href="http://trainz.vtsim.com/others.htm" border="0"><img src="http://www.vtsim.com/image/b_trz_others_i.png"></a><a href="mailto:vasco@vtsim.com" border="0"><img src="http://www.vtsim.com/image/b_email.png"></a><br />
<img src="http://www.vtsim.com/image/sep_800.png">
</p>
//--- and the menu code ended here
<p align="center">
Contents will display here
</p>
</font>
</body>
</html>
最佳答案
基本上将您的 header 包装在一个容器中,并带有一点 jQuery
像这样:
$(window).scroll(function () {
if ($(window).scrollTop() > 226) {
$(".header").addClass("fixed");
} else {
$(".header").removeClass("fixed");
}
});
你给这个容器添加一个类,让它成为fixed
向下滚动 226 像素后(内容超过标题高度)。
CSS:
.fixed {
position:fixed;
width:100%;
top:0;
left:0;
}
编辑:要在您的网站中轻松实现此脚本,只需在 </head>
之前添加此代码即可在您的 html 中标记:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(window).scroll(function () {
if ($(window).scrollTop() > 226) {
$(".header").addClass("fixed");
} else {
$(".header").removeClass("fixed");
}
});
</script>
<style type="text/css">
.fixed {
position:fixed;
width:100%;
top:0;
left:0;
}
</style>
并且不要忘记添加 <div class="header">
也与 fiddle 示例中一样。
关于html - 滚动时如何使页面的一部分固定在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951190/