2013-08-01 3 views
0

안녕하세요 저는 클릭 한 후에 요소로 페이지를 스크롤하는 코드를 작성했지만 부드러운 스크롤을하기 전에 페이지의 맨 위로 이동합니다. 누군가 내가 잘못하고있는 것을 설명 할 수 있습니까? jQuery - div 로의 부드러운 스크롤

스크립트

$('a[href*="#"]').click(function(e){ 
     e.preventDefault(); 
    if($(this).attr('href') == '#') { 
     $('html, body').animate({ 
     scrollTop: $('body').offset().top 
     }, 1000); 
     window.location.hash = ''; 
    } else { 
     $('html, body').animate({ 
      scrollTop: $($.attr(this, 'href')).offset().top - $(this).height() 
     }, 1000); 
     window.location.hash = $(this).attr('href'); 
    } 
     return false; 
}); 

내가 JS를 배울 수있는 곳 말해입니다 :)

+0

학습을위한 링크와 Masterin을 따라 가세요. g JS : http://stackoverflow.com/questions/2687566/learning-javascript-in-one-weekend http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript –

+0

이 줄을 window.location.hash = '''에 두는 이유는 무엇입니까? 이 줄을 써 보지 않으셨습니까? – anu

+0

예 그것의 많은 구성을 tryed했지만 여전히 파이어 폭스에서 "점프"합니다. – arclite

답변

0

http://css-tricks.com/snippets/jquery/smooth-scrolling/이 내가 내 질문을 해결 한이 그것입니다 메뉴

//menu smooth scroll to element 
    $('a[href^="#"]').on('click',function(e){ 
     $target = $(this).attr('href'); 
     e.preventDefault(); 
     $('.active').removeClass('active'); 
     $(this).addClass('active'); 
     if($(this).attr('href') == '#') { 

      $('html, body').stop().animate({ 
      scrollTop: $('body').offset().top 
      }, 1000, function(){location.hash = $target;}); 
     } else { 
      $('html, body').stop().animate({ 
       scrollTop: $($target).offset().top + 57 - $('.menu').height() 
//this is important to add + height of menu holder div in my case it's 57 this removes jump effect in firefox 
      }, 1000,function(){location.hash = $target}); 

     } 
     return false; 
    }); 

에 대한 스크립트를 수정

<div class="menu"> 
    <div class="top"> 
    <ul class="menu_list"> 
     <li><a href="#">Start</a></li> 
     <li><a href="#o_nas">About</a></li> 
     <li><a href="#services">Services</a></li> 
     <li><a href="#portfolio">Portfolio</a></li> 
     <li><a href="#contact">Contact</a></li> 
    </ul> 
    </div> 
</div> 

메뉴의 HTML입니다, 위의 코드가 나에게 완벽하게 작동하고 나는 여기에 나와 같은 다른 프로그래머들을 위해 두었습니다.) 그리고 URL 변경과 부드러운 스크롤 효과를 가진 단일 페이지 사이트를 얻었습니다 : P

0

이 튜토리얼 및 데모는 그것을 달성하는 방법을 보여줍니다 바랍니다. 그것을 한번보세요.

+0

이것은 내 스크립트가 Chrome에서 훌륭하게 작동하지만 Firefox에서는 제대로 작동하지 않습니다. url은 변경되지만 스크롤 한 후에는 요소로 이동하고 클릭 한 후에는 사이트의 맨 위로 이동합니다. – arclite