ページ内リンクを指定する時に、急に画面が切り替わると現在の場所を見失うことがあります。
それを、解消するためにスクロールで指定の位置まで移動する設定にjQueryを使って行います。
■ページ内リンクをスクロールで移動するやり方
1.ボタンを作成します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<a href="#bottom">ボタン</a> |
2.head内でjQueryを呼び出します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> |
3.その後に以下のスクリプトを記入します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
$(function(){ | |
$('a[href^=#]').click(function(){ | |
var speed = 500; | |
var href= $(this).attr("href"); | |
var target = $(href == "#" || href == "" ? 'html' : href); | |
var position = target.offset().top; | |
$("html, body").animate({scrollTop:position}, speed, "swing"); | |
return false; | |
}); | |
}); | |
</script> |
★完成★
webサイトを作る際は、そのサイトを見るユーザーがいかに見やすいかを意識して作るように心がけましょう。
<参考サイト>
【jQuery】ページ内リンクをするするーっとスムースにスクロールするJavascript | KLUTCHE