html标签使用定位时,自动居中技巧

例:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>置顶菜单</title>
 6 
 7     <script type="text/javascript" src="../js/jquery-1.12.4.min.js"></script>
 8     <script type="text/javascript">
 9         $(window).scroll(function(){   //页面滚动事件
10             var nowtop=$(document).scrollTop();  //获取页面向上滚动距离
11             //console.log(nowtop);
12 
13             if(nowtop>200){
14                 $('.menu').css({
15                     position:'fixed',
16                     top:0,
17                     left:'50%',      //和下面的marginLeft结合使用,使.menu居中
18                     marginLeft:-480,
19                 });
20                 $('.menu_pos').show()     //和下面的$('.menu_pos').hide()结合使用,当nowtop>200时,menu_pos和menu有重合,消除滑动滚动条时menu_pos卡顿效果(造成卡顿的原因是fix定位脱离了文档流导致)
21                 }
22             else{
23                 $('.menu').css({
24                     position:'static',   //static 默认值,没有定位,元素出现在正常的文档流中,相当于取消定位属性或者不设置定位属性
25                     marginLeft:'auto'   //这里需要有marginLeft,为了覆盖上面的marginLeft:-480
26                 });
27                 $('.menu_pos').hide()
28             }
29 
30         })
31     </script>
32 
33     <style type="text/css">
34         body{margin:0px;}
35         .logo_bar{
36             width:960px;
37             height:200px;
38             background-color:#f0f0f0;
39             margin:0 auto;
40 
41         }
42         .menu,.menu_pos{
43             width:960px;
44             height:50px;
45             margin:0 auto;
46             background-color:gold;
47             text-align:center;
48             line-height:50px;
49         }
50         .menu_pos{
51             display:none;
52         }
53 
54         .down_con{
55             width:960px;
56             height:1800px;
57             margin:0 auto;
58         }
59 
60         .down_con p{
61             margin-top:100px;
62             text-align:center;
63         }
64         .totop{
65             width:50px;
66             height:50px;
67             background:url(images/up.png) center center no-repeat #000;
68             border-radius:50%;
69             position:fixed;
70             right:50px;
71             bottom:50px;
72             display:none;
73         }
74     </style>
75 
76 </head>
77 <body>
78     <div class="logo_bar">顶部logo</div>
79     <div class="menu">置顶菜单</div>
80     <div class="menu_pos"></div>
81     <div class="down_con">
82         <p style="color:red">网站主内容</p>
83         <p>网站主内容</p>
84         <p>网站主内容</p>
85         <p>网站主内容</p>
86         <p>网站主内容</p>
87     </div>
88     <a href="javascript:;" class="totop"></a>
89 </body>
90 </html>

 

posted on 2019-12-22 20:58  cherry_ning  阅读(542)  评论(0)    收藏  举报

导航