导航条随屏幕滚动,一定距离后fixed

描述

导航条随屏幕滚动,一定距离后fixed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.wrapper{width:1000px;height:2000px;margin-left:auto;margin-right:auto;}
.header{height:150px;}
#nav{padding:10px;position:relative;top:0;background:black;width:1000px;}
a{display:inline-block;margin:0 10px;*display:inline;zoom:1;color:white;}
</style>
</head>
<body>
<div class="wrapper">
<div class="header"></div>
<div id="nav">
<a href="#">11111</a>
<a href="#">22222</a>
<a href="#">33333</a>
<a href="#">44444</a>
<a href="#">55555</a>
</div>
</div>
</body>
</html>
<script>
function menuFixed(id){
var obj = document.getElementById(id);
var _getHeight = obj.offsetTop;
window.onscroll = function(){
changePos(id,_getHeight);
}
}
function changePos(id,height){
var obj = document.getElementById(id);
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
console.log(scrollTop+'scroll')
console.log(height+'off')
if(scrollTop < height){
obj.style.position = 'relative';
}else{
obj.style.position = 'fixed';
}
}
</script>
<script type="text/javascript">
window.onload = function(){
menuFixed('nav');
}
</script>

效果: