jQueryを使って画面をスムーズにスクロール
コチラを使うためにはjQueryが必要です。
jQueryは< head>~</ head>の間に下記のようなタグを入れることで使うことができます。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
テスト用のコードです。
test.css
body {
height: 2000px;
}
#test {
margin-top: 1500px;
}
test.html
<html>
<head>
<title></title>
</head>
<body>
<button id="btn">スクロール</button>
<div id="test">hello</div>
</body>
</html>
test.js
$(document).ready(function() {
$(document).on("click", "#btn", function() {
$("html, body").animate( {scrollTop: $("#test").offset().top}, 100 );
});
});
一つのファイルでまとめてテストすることも可能です。
test.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title></title>
<style>
body {
height: 2000px;
}
#test {
margin-top: 1500px;
}
</style>
</head>
<body>
<button id="btn">スクロール</button>
<div id="test">hello</div>
<script>
$(document).ready(function() {
$(document).on("click", "#btn", function() {
$("html, body").animate( {scrollTop: $("#test").offset().top}, 100 );
});
});
</script>
</body>
</html>
説明としては
$(document).on("click", "#btn", function() {
$("html, body").animate( {scrollTop: $("#test").offset().top}, 100 );
});
1.btnというIDを持つ要素(id="btn"のボタン)がクリック(click)された時処理を実行します。
2.animateというjQueryを関数を使います。animateは画面や要素を動かせる関数です。
3.画面のスクロールをtestというIDを持つ要素の位置に持っていきます。最後の「100」は速度です。