2
0

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.

HTML スクロール時に背景画像を遅らせる

Posted at

後でコピペできるように残しておきます。

↓わかりにくいですが一応GIF

ダウンロード.gif

注意

スクロール時の背景画像の滑らかさはモニターのスペックに依存してしまうので、スペックの低いモニターだと結構カクツキます。
ゲーミングモニターだと滑らかに動くので良きですが...

下記のコードではScrollイベントを使って背景画像のポジションを弄っているのですが、カクツキを完全になくすためならrequestAnimationFrameやsetIntervalを使わないとダメかも。

準備

背景に使用する画像を、bg.pngという名前で準備しておきました。

HTML

  <div id="bg" class="ly_bg"></div>

CSS

  .ly_bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: -1;
    background-image: url('../images/bg.png');
    background-size: 100% auto;
    background-repeat: repeat-y;
    background-position-y: 0;
  }

JS

let bg = document.getElementById('bg')
const rate = 3

window.addEventListener('scroll', function () {
  let y = window.scrollY
  bg.style.backgroundPositionY = `-${y / rate}px`
})
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?