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 3 years have passed since last update.

【jQuery】ページのスクロールで背景色を変える。

Posted at

やりたいこと

特定の範囲内でページがスクロールされている時だけ背景色を変えたい。

完成形

Image from Gyazo

1. HTMLの準備

sample.html
<div class="title">
 Works
</div>
<div class="color-man">  ⬅️背景色を変えるところ
  <img src="img/ruby.png" class="ruby-image">
  <img src="img/ruby.png" class="ruby-image">
</div>  

2. CSSの準備

適当に横並びにして、幅と高さを与えておきます。

sample.css
  .color-man {
    margin: 0 auto;
    border-radius: 10px;
    padding: 20px;
    width: 900px;
    height: 300px;
    display: flex;
    justify-content: space-between;
  }
  
  .ruby-image {
    width: 300px;
    cursor: pointer;
  }

3. JSの準備

スクロール量を取得し、その量によって背景色を変える記述と戻す記述をする。

sample.js
window.onscroll = function(){
  var scrollTop = window.pageYOffset ;   //スクロール量を取得
  if (scrollTop > 900 ) {   
    $('.color-man').css('background-color', 'skyblue');
    $('.color-man').css('transition', '1.3s')
  }
  if (scrollTop < 1400 ) { 
    $('.color-man').css('background-color', '');
    $('.color-man').css('transition', '1.0s')
  }
}

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

0
1
1

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?