2017-10-20 3 views
1

topNavからスムーズなスクロール効果をWebページのさまざまなセクションに作成しようとしています。下のコードでは、私が持っている問題を再現しました。単純にスクロール・プロセスをアニメーション化できないようです。私のリンクは適切なセクションにジャンプし、私は'click'の時点で適切な要素がつかんでいることを確認するために道に沿ってconsole.loggedを持っていますが、それでも動作しません。Offset.topを使用したJquery Smooth Scroll

誰でも手助けできますか?最初は、navlinks個の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

私はそれがロードされていません。ああ!あなたのソリューションをありがとうございました。 –

関連する問題