用JS实现在滚动一定距离后,导航栏部分布局发生变化,固定到窗口指定位置,且始终不变。再次回滚后,导航栏布局恢复。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>导航栏滚动后变为固定定位</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
font-size: 40px;
font-family: '宋体';
text-align: center;
line-height: 100px;
width: 100%;
}
/*头部*/
.top {
position: fixed;
top: 0px;
left: 0px;
height: 100px;
background: blue;
}
/*搜索栏部分*/
.nav {
height: 100px;
background: red;
}
/*导航栏部分*/
.nav2 {
height: 100px;
background: yellowgreen;
}
/*内容部分*/
.test {
background: pink;
height: 1000px;
padding-top: 100px;
}
/*导航栏变为固定定位*/
.fixednav {
position: fixed;
top: 100px;
left: 0px;
}
</style>
</head>
<body>
<div style="height:100px"></div>
<div class="top">头部</div>
<div class="nav">搜索栏</div>
<div class="nav2">导航栏</div>
<div class="test">内容</div>
</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(window).scroll(function() {
if($(document).scrollTop() >= 200) {
$(".nav2").addClass("fixednav").slideDown();
} else if($(document).scrollTop() < 200) {
$(".nav2").removeClass("fixednav").slideDown();
}
})
})
</script>