본문 바로가기
Js

offset().top 메뉴 스크롤하기

by 영감은어디에 2024. 6. 29.

<div class="wrap">
  <div id="top_menu">		
    <div id="logo">
      <a href="#home"><img src="img/logoPaper.png" alt="Paper" /></a>
    </div>
    <ul>
      <li class="on"><a href="#paper">paper</a></li>
      <li><a href="#works">works</a></li>
      <li><a href="#email">email</a></li>
    </ul>
  </div>
  <div id="contents">
    <div id="paper"><img src="img/paper.jpg" alt="paper" /></div>
    <div id="works"><img src="img/work.jpg" alt="works" /></div>
    <div id="email"><img src="img/email.jpg" alt="email" /></div>
  </div>
</div>

 

$(function(){
  var menu = $('#top_menu > ul > li');
  var contents = $('#contents > div');
  
  menu.click(function(e){
      e.preventDefault();
      $(this).addClass('on').siblings().removeClass('on');
      var tg = $(this);
      var i = tg.index();
      var section = contents.eq(i);
      var tt = section.offset().top;
      $('html, body').stop().animate({scrollTop:tt});
  });
  
    $(window).scroll(function(){
      var sctop = $(window).scrollTop();
      contents.each(function(){
        var i = $(this).index();
        if(sctop + 50 >= $(this).offset().top){ // 여유분50
            menu.removeClass('on');
            menu.eq(i).addClass('on');
        }
    });
  });
});