我是实习生,很多东西都不懂,最近发现很多网站的导航都会一直悬挂在窗口顶部,自己学习了一下,仿照别人写出了如下例子,没做什么CSS样式,只是体现如何实现。
代码如下:
<!DOCTYPE html>
<html><head><title>仿照导航顶部浮动效果</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var h = $("#header").height();//获取顶部高度
var nav = $(".nav");
$(window).scroll(function(){
if($(window).scrollTop() > h){//滚动大于顶部高度,添加置顶类
nav.addClass("navfl");
nav.removeClass("nav");
}else{
nav.addClass("nav");
nav.removeClass("navfl");
}
});
})
</script>
<style type="text/css">
#header{100%;height:80px;background:#2C9BD6;}
.nav{100%;height:50px;border:2px solid #ff1010;color:#333}
.navfl{position:fixed;left:0;margin:0;top:0;}
</style>
</head>
<body style="zoom: 1;" contenteditable="true">
<div id="header"></div>
<div class="nav">
<div style="text-align:center"><h1>this is the nav!</h1><h2></h2></div>
</div>
<div>
<div style="text-align:center;height:300px;"><h1>1</h1><h2></h2></div>
<div style="text-align:center;height:300px;"><h1>2</h1><h2></h2></div>
<div style="text-align:center;height:300px;"><h1>1</h1><h2></h2></div>
<div style="text-align:center;height:300px;"><h1>1</h1><h2></h2></div>
<div style="text-align:center;height:300px;"><h1>1</h1><h2></h2></div>
<div style="text-align:center;height:300px;"><h1>1</h1><h2></h2></div>
</div>
</body></html>