滑动导航栏固定

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>滑动导航栏固定</title>
<style type="text/css">
  *{padding: 0px;margin: 0px;}
  .home_top{height: 400px;background-color: #4BC5F2;text-align: center;font-size: 24px;line-height: 400px;}
  #mainMenuBar{width: 100%;height: 100px;background-color: #D4C76D;text-align: center;font-size: 20px;line-height: 100px;border-bottom: 1px solid #000;}
  .content{height: 1200px;background-color: #F7CAA6;text-align: center;padding-top: 50px;font-size: 36px;}
  .stick {position: fixed;top: 0;}
</style>
</head>
<body>
<div id="wrapper">
  <div id="container">
    <div class="home_top">header_top</div>
  </div>
  <div id="mainMenuBarAnchor"></div>
  <div id="mainMenuBar">menu_nav</div>
  <div class="content">content</div>
</div>
<script src='http://libs.baidu.com/jquery/1.9.0/jquery.min.js'></script> 
<script style='text/javascript'>
  $(document).ready(function() {
    var $window = $(window),
        $mainMenuBar = $('#mainMenuBar'),
        $mainMenuBarAnchor = $('#mainMenuBarAnchor');
       
        // Run this on scroll events.
        //scroll()
        //当用户滚动指定的元素时,会发生scroll事件。
        //scroll事件适用于所有可滚动的元素和window对象(浏览器窗口)
        //scroll()方法触发scroll事件,或规定当发生scroll事件时运行的函数
        $window.scroll(function() {
          //scrollTop()方法返回或设置匹配元素的滚动条的垂直位置
          var window_top = $window.scrollTop();
          //javascript用offsetTop();jquery用offset().top;
          var div_top = $mainMenuBarAnchor.offset().top;
            if (window_top > div_top) {
              // Make the div sticky.
              $mainMenuBar.addClass('stick');
              // $mainMenuBarAnchor.height($mainMenuBar.height());
            }
            else {
              // Unstick the div.
              $mainMenuBar.removeClass('stick');
              // $mainMenuBarAnchor.height(0);
            }
          });
  });

</script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值