2017-10-20 21 views
1

topNav에서 웹 페이지의 다양한 섹션으로 부드러운 스크롤 효과를 만들려고합니다. 아래 코드에서 필자는 가지고있는 문제를 재현했습니다. 단순히 스크롤 프로세스를 애니메이션화 할 수없는 것 같습니다. 내 링크가 적절한 섹션으로 건너 뛰고, 은 올바른 요소가 'click'의 시간에 잡혀 있는지 확인하는 길에 있지만 여전히 작동하지 않습니다.Offset.top을 사용하여 Jquery 부드러운 스크롤

누구든지 도와 줄 수 있습니까? 처음에는 개별 ID를 navlinks 개 부여하는 대신 클래스 이름으로 그룹화했다고 생각했습니다. 그게 내 문제의 일부가 될 수 있을까?

$(document).ready(function() { 
 
\t 
 
\t $('.slide').click(function() { 
 
\t \t 
 
\t \t var link = $(this).attr('href'); 
 
\t \t 
 
\t \t $('html,body').animate({ 
 
\t \t \t scrollTop: $(link).offset().top}, 1000); 
 
\t \t return false; 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t \t 
 
\t }); 
 
\t 
 
\t 
 
\t 
 
});
* { 
 
\t padding: 0; 
 
\t margin: 0; 
 
} 
 

 
nav { 
 
\t width: 100%; 
 
\t height: 120px; 
 
} 
 

 
div { 
 
\t width: 100%; 
 
\t height: 500px; 
 
}
<nav> 
 
\t <a href="#first" class="slide">Section 1</a> 
 
\t <a href="#second" class="slide">Section 2</a> 
 
\t <a href="#third" class="slide">Section 3</a> 
 
\t <a href="#fourth" class="slide">Section 4</a> 
 
</nav> 
 

 
<div> 
 
\t <a name="first">Section 1</a> 
 
</div> 
 

 
<div> 
 
\t <a name="second">Section 2</a> 
 
</div> 
 

 
<div> 
 
\t <a name="third">Section 3</a> 
 
</div> 
 

 
<div> 
 
\t <a name="fourth">Section 4</a> 
 
</div>

답변

2

먼저, 당신은 당신의 프로젝트에 JQuery와로드 했습니까?

그렇다면 HTML에서 약간 실수를 한 것입니다. Href 속성은 이름 속성이 아니라 ID를 참조합니다!

내 솔루션 :

$(document).ready(function() { 
 
\t 
 
\t $('.slide').click(function() { 
 
\t \t 
 
\t \t var link = $(this).attr('href'); 
 
\t \t 
 
\t \t $('html, body').animate({ 
 
\t \t \t scrollTop: $(link).offset().top}, 1000); 
 
\t \t return false; \t 
 
\t }); 
 
});
* { 
 
\t padding: 0; 
 
\t margin: 0; 
 
} 
 

 
nav { 
 
\t width: 100%; 
 
\t height: 120px; 
 
} 
 

 
div { 
 
\t width: 100%; 
 
\t height: 500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<nav> 
 
\t <a href="#first" class="slide">Section 1</a> 
 
\t <a href="#second" class="slide">Section 2</a> 
 
\t <a href="#third" class="slide">Section 3</a> 
 
\t <a href="#fourth" class="slide">Section 4</a> 
 
</nav> 
 

 
<div id="first"> 
 
\t <a>Section 1</a> 
 
</div> 
 

 
<div id="second"> 
 
\t <a>Section 2</a> 
 
</div> 
 

 
<div id="third"> 
 
\t <a>Section 3</a> 
 
</div> 
 

 
<div id="four"> 
 
\t <a>Section 4</a> 
 
</div>

+0

나는로드해야합니까. 아! 당신의 솔루션에 너무 감사드립니다. –