iT邦幫忙

0

使用JQuery設定Sticky Header

Stickyheader的HTML

<header class="page-header">
  <div class="inner">
    <h1 class="site-logo">
      <a href="">
        <img src="https://ithelp.ithome.com.tw/storage/image/nav_logo.svg" alt="" height="65" width="200">
      </a>
    </h1>
    <nav class="primary-nav">
      <ul>
        <li><a href="">About</a></li>
        <li><a href="">Work</a></li>
        <li><a href="">Blog</a></li>
        <li><a href="">Recruit</a></li>
        <li><a href="">Contact</a></li>
      </ul>
    </nav>
  </div>
</header>

Stickyheader的CSS

.page-header{
  background-color: #fff;
  position: absolute;
  width: 100%;
  min-width: 960px;
  background-color: #000;
  .inner{
    margin: auto;
    width: 960px;
    >*{
      display: inline-block;
    }
  }
  nav{
    float: right;
  }
  h1{
    margin: 0;
  }
  ul{
    li{
      list-style: none;
      display: inline-block;
      a{
        color: #fff; 
        text-decoration: none;
        padding: 0 6px;
      }
    }
  }
}

.page-header.sticky{
  position: fixed;
  top: 0;
}

最後設定JQuery

$(function(){
  $('.page-header').each(function(){
    var $window = $(window),
        $header = $(this),
        headerOffsetTop = $header.offset().top;
    $window.on('scroll',function(){
      if($window.scrollTop()>headerOffsetTop){
        $header.addClass('sticky');
      } else{
        $header.removeClass('sticky');
      }
    });
    $window.trigger('scroll');
  });
});

範例網址


尚未有邦友留言

立即登入留言