LoginSignup
0
0

More than 5 years have passed since last update.

jquery、画面スクロールの簡単な例

Posted at

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」は速度です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0