2017-10-09 1 views
0

동일한 페이지에서 각 ID 위치를 '부드럽게 스크롤'링크를 원한다면 상단과의 거리가 50px 이 위치에서 국경. 부드러운 스크롤은 잘 작동하며 위쪽 테두리가있는 정확한 위치로 스크롤하는 것처럼 보입니다.사이트에서 타겟 ID로 부드럽게 스크롤하면 .offset()에도 불구하고 화면 상단 경계로 이동합니다. 상단 - 50

갑자기 (몇 밀리 초 후) 페이지가 위쪽 테두리로 이동합니다 ('.offset(). top-50'이 무언가에 의해 덮어 쓰여지는 것처럼). 여기서 일어나는 일과 어떻게이 문제를 해결할 수 있습니까? 참고로 나는 1920px 뷰포트의 폭, 윈도우 시스템에서 크롬을 사용하고

$(function() { 
 
    // Add smooth scrolling to all links 
 
    $("a").on('click', function(event) { 
 
    // Make sure this.hash has a value before overriding default behavior 
 
    if (this.hash !== "") { 
 
     // Prevent default anchor click behavior 
 
     event.preventDefault(); 
 
     var hash = this.hash; 
 
     // 800 = milliseconds it takes to scroll; - 50 = vertical location 
 
     $('html, body').animate({ 
 
     scrollTop: $(hash).offset().top - 50 
 
     }, 800, function(){ 
 
     // Add hash (#) to URL when done scrolling (default click behavior) 
 
     window.location.hash = hash; 
 
     }); 
 
    } // End if 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a class="nav-link" href="#about">About</a> 
 
<div style="height: 2000px">testdiv before</div> 
 
<p style="height: 100px" id="about">target text to scroll and stop 50px above upper border</p> 
 
<div style="height: 2000px">testdiv after</div>

.

+0

인한하면 window.location.hash = 해시'에 일어날 것 같습니다;'. https://jsfiddle.net/nd9ot0k3/1/ –

답변

0
// Add hash (#) to URL when done scrolling (default click behavior) 
    window.location.hash = hash; 

이런 일이 발생합니다. 해시를 넣으면 브라우저에 요소 # hashname이 있으면 브라우저가이를 스크롤합니다. 즉, onhashchange 이벤트에 전체 논리를 이동하고 거기에서 애니메이션을 유발하는 것입니다 주위에

$('html, body').animate({ 
     scrollTop: $(hash).offset().top - 50 
     }, 800, function(){ 
     // Add hash (#) to URL when done scrolling (default click behavior) 
     window.location.hash = hash; 
     }); 

유일한 방법은 이동 : 그것은 당신이 여기에서 제공하는 콜백에서 발생합니다. 당신은 같은 것을 수행해야합니다 : 당신은 그것의 많은의 데이터를 얻을 수 있도록

은 "핸들러"기능 "E"PARAM 내부
function handler(e){ 
    e.preventDefault(); 

    // scroll logic here 
} 

window.addEventListener("hashchange", handler, true); 

이벤트 객체에 대한 참조입니다. 창을 파싱 할 수 있습니다. 위치를 이동하려면 정확한 해시를 얻으십시오. 코드 대신 $ (window.location.hash) 같은 것이 있습니다. 여기

확인 : https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange https://developer.mozilla.org/en-US/docs/Web/API/Event