- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
- <script>
- // 定义菜单栏离页面顶部的距离,默认为200
- var divOffsetTop = 200;
- //滚动事件
- window.onscroll=function(){
- var div = document.getElementById("divId");
- // 计算页面滚动了多少(需要区分不同浏览器)
- var topVal = 0;
- if(window.pageYOffset){//这一条滤去了大部分, 只留了IE678
- topVal = window.pageYOffset;
- }
- else if(document.documentElement.scrollTop ){//IE678 的非quirk模式
- topVal = document.documentElement.scrollTop;
- }
- else if(document.body.scrolltop){//IE678 的quirk模式
- topVal = document.body.scrolltop;
- }
- if(topVal <= divOffsetTop){
- div.style.position = "";
- }
- else {
- div.style.position = "fixed";
- }
- };
- // 页面加载完之后,计算菜单栏到页面顶部的实际距离
- window.onload=function(){
- var div = document.getElementById("divId");
- divOffsetTop = div.offsetTop;
- };
- </script>
- </head>
- <body>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- aaaaaaaaaaaaaaaaaaaaaaa<br>
- <div id="divId" style=" 500px; height: 40px; line-height: 40px; top: 0px; background: pink">假设这是菜单栏,在页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