2013-12-10 4 views
3

위로부터 오프셋을 추가하고 다음 함수로 부드럽게 스크롤하려합니다. 기능은 하나의 버튼에 고정되어 있으며 페이지 아래로 사용자를 따라갑니다. 이 버튼은 수많은 앵커를 스크롤 한 다음 첫 번째 페이지로 돌아갈 수 있어야하며 이상적으로 상단에서 105 픽셀의 오프셋이 있어야합니다. 도움을위한 몇 시간 동안 그물을 trawled 그리고 jquery이 해결하기 위해 자신을 어떻게 알지 말아, 어떤 도움 ?? 여기 비슷한 예 - http://www.google.com/nexus/7/ (오른쪽 아래에있는 버튼)함수에서 부드러운 스크롤 + 오프셋 goToNext

<script> 
var max = 6; 

function goToNext() { 
    var hash = String(document.location.hash); 
    if (hash && hash.indexOf(/anchor/)) { 
     var newh = Number(hash.replace("#anchor","")); 
     (newh > max-1) ? newh = 0 : void(null); 
     document.location.hash = "#anchor" + String(newh+1); 
    } else { 
     document.location.hash = "#anchor1";   
    } 
} 

</script> 
<a href="#" onclick="goToNext();return false;"></a> 

<div id="anchor1"></div> 
<div id="anchor2"></div> 
<div id="anchor3"></div> 
<div id="anchor4"></div> 
<div id="anchor5"></div> 
<div id="anchor6"></div> 

답변

3

당신은 animate({scrollTop:value},delay)를 사용하여 요소에 원활을 을 스크롤 할 수 있습니다.

$('document').ready(function() { 
    //on DOM ready change location.hash to 'anchor1' 
    window.location.hash = 'anchor1'; 
    //GO TO NEXT click event: 
    $('a').click(function (e) { 
     //preventing the default <a> click (href="#") 
     e.preventDefault(); 
     //get the current hash to determine the current <div> id 
     var hash = window.location.hash, 
      //find the (next) immediate following sibling of the current <div> 
      $next = $(hash).next('div'); 
     //check if this next <div> sibling exist 
     if ($next.length) { 
      var id = $next.attr('id'), 
       nextOffsetTop = $next.offset().top; 
      //animate scrolling and set the new hash 
      $('body, html').animate({scrollTop: nextOffsetTop}, 'slow'); 
      window.location.hash = id; 
     }else{ 
     //else if the next <div> sibling does not exist move to the first anchor 
      var first = '#anchor1'; 
      $('body, html').animate({scrollTop: $(first).offset().top},'slow'); 
      window.location.hash = first; 
     } 

    }); 
}) 

이 부분은 jsfiddle입니다.


그런 다음을 깜빡 거림 온다. 실제로 위의 코드를 자세히 살펴보면 깜박임은 아니지만 다소 바보입니다. 먼저 animate(scrollTop)을 설정 한 다음 해시를 변경합니다. window.location.hash = id. 이제 애니메이션이 스크롤을 시작하고 갑자기 해시를 변경하면 다음 <div> (기본값 인 haschange 이벤트)으로 직접 이동하지만 animate()에 의해 뒤로 당겨서 스크롤하면 저크이됩니다.

haschange 이벤트의 기본 전파를 중지 할 수는 없지만 모든 브라우저에서 작동 할 수 있다고 보장 할 수는 없습니다. 각 브라우저는 haschange 이벤트와 관련하여 각기 다른 동작을합니다. 하지만 당신이 제공 한 게시물에 @ 앤디 E 솔루션 덕분에, 우리는 haschange 전파를 중단시킬 필요가 없습니다. 해시를 먼저 변경하고 마지막으로 scrollTop() 위치로 재설정 한 다음 마음대로 스크롤 할 수 있습니다!

//get the current scrollTop value 
var st = $(window).scrollTop(); 
//change the hash 
window.location.hash = id; 
//reset the scrollTop 
$(window).scrollTop(st); 
//animate scrolling 
$('body, html').animate({scrollTop: nextOffsetTop}, 'slow'); 

업데이트 내용 확인 jsfiddle.


이제 HTML5 History API에 대해 이야기 해 봅시다. 이것은 HTML5 (특히 IE) 브라우저에서 다르게 구현되고 HTML4 브라우저에 대한 대체 기능이 없기 때문에 처음에는이 기능을 도입하지 않은 이유로이 방법이 어떻게 든 일관성이 없기 때문입니다. 그러나 당신은 내가 추측하는 플러그인을 사용하여 이것을 올바르게 수행 할 수 있습니다. 여기

history.pushState()를 사용하여 할 수있는 방법은 다음과 같습니다

if ($next.length) { 
    var id = $next.attr('id'), 
     nextOffsetTop = $next.offset().top; 

    history.pushState({state:id}, id, '#'+id); 
    $('body, html').animate({scrollTop: nextOffsetTop - 105}, 'slow');  
} 

jsfiddle를 참조하십시오.

그게 전부입니다. 건배!

+0

한 버튼의 기능을 고정시키고 사용자를 페이지 아래로 따라 가고 싶습니다. 이 버튼은 수많은 앵커를 스크롤 한 다음 첫 번째 페이지로 돌아갈 수 있어야하며 이상적으로 상단에서 105 픽셀의 오프셋이 있어야합니다. 제공되는 코드를 수정하는 방법이 있습니까 (감사합니다! 스크롤 문제가 해결됨). 마지막 앵커가 눌린 후 맨 위로 스크롤하려면 어떻게해야합니까? 답변 해 주셔서 감사합니다. – webbist

+0

$ ('body, html').움직이기 ({scrollTop : nextOffsetTop - 105}, 'slow'); 이렇게 편집하면 내 오프셋과 부드러운 매끄러운 스크롤이 가능하지만 마지막 앵커에 도달하면 맨 위에서 반복되도록하는 방법 ?? – webbist

+1

요소가 상쇄되기 전에 105의 위쪽 간격이 필요합니다. 이 [** jsfiddle **] (http://jsfiddle.net/LR9Cd/8/)을 업데이트했습니다. –