2017-10-20 107 views
1

我試圖創建從topNav到網頁上各個部分的平滑滾動效果。在下面的代碼中,我重新創建了我遇到的問題,這只是我似乎無法使滾動過程動畫。我的鏈接跳轉到正確的部分,我沿着console.logged確保正確的元素在'click'時被抓取,但它仍然不起作用。Jquery平滑滾動使用Offset.top

任何人都可以協助嗎?起初,我認爲這可能與這樣一個事實有關,即不是給予個人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 \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

我有它加載。啊!非常感謝你的解決方案。 –