0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【jQuery】ぺージのスクロールボタンを作りたい

Posted at

ページの一番上や、特定の位置にスクロールさせるボタンを設置する際の
簡潔な手順をご紹介。

1. htmlでボタンを準備

今回はフッターの中に設置しました。

sample.html
<div class="footer">
  <div class="footer__btn">
    Page Top
  </div>
</div>

2. 位置を固定する

スクロール中に隠れないように、「z-index」も調整しておきます。

sample.css
.footer__btn {
  cursor: pointer;
  height: 80px;
  width: 80px;
  z-index: 10;
  position: fixed;
  bottom: 20px;
  right: 32px;
  background-color: red;
  line-height: 80px;
  text-align: center;
  font-size: 20px;
}

3. jsを準備する

ボタンのクリックイベントによって、ページの最上部までスクロールさせます。

sample.js
var scrollTop = window.pageYOffset ;     //スクロール量を取得
  $(".footer__btn").on("click", function(){   //クリックした時に発火
    $( 'html,body' ).animate( {scrollTop:0}, 'slow' );  //ゆっくり一番上までスクロールさせる
  })
  $(".gy-btn").on('click', function(){
    $( 'html,body' ).animate( {scrollTop:1500}, 'slow' );
  })

ヘッダーのボタン等で指定位置までスクロールさせたい場合は
scrollTopの値を変更します。

sample.js
var scrollTop = window.pageYOffset ;     
  $(".other-btn").on('click', function(){
    $( 'html,body' ).animate( {scrollTop:1500}, 'slow' );
  })

以上で終了です。
ご覧いただきありがとうございました。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?