jQuery实现固定导航栏效果

jQuery实现固定导航栏效果:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>固定导航栏效果</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
text-align: center;
}
.fixed{
top: 0;
left: 0;
position: fixed;
}
</style>
<script type="text/javascript" src="js/jquery-3.2.1.min.js" ></script>
<script>
$(document).ready(function(){
// 入口函数
$(window).scroll(function(){
// 添加滚动事件
if($(window).scrollTop() >= $(".top").height()){
// 判断窗口的滚动如果大于top的高度就为nav添加fixed
$(".nav").addClass("fixed");
}else{
// 否则就为nav移除fixed
$(".nav").removeClass("fixed");
}
});
});
</script>
</head>
<body>
<div class="top">
<img src="img/top.png"/>
</div>
<div class="nav">
<img src="img/nav.png"/>
</div>
<div class="main">
<img src="img/main.png"/>
</div>
</body>
</html>