h1 ↓下にスクロールしてください↓
.container
View Compiled
.container {
  margin: 30% 0;
  width: 100%;
  height: 480px;
  background-image: url(https://i.imgur.com/s6MKAA2.jpg);
  background-size: cover;
  background-position: center top;
  background-attachment: fixed;
  }
View Compiled
class ParallaxEffectBackground {
  constructor() {
    this.devided = 5;
    this.target = '.container';
    this.setBackgroundPosition();
  }

  getScrollTop() {
    return Math.max(
      window.pageYOffset,
      document.documentElement.scrollTop,
      document.body.scrollTop,
      window.scrollY
    );
  }

  setBackgroundPosition() {
    document.addEventListener('scroll', e => {
      const scrollTop = this.getScrollTop();
      const position = scrollTop / this.devided;
      console.log('scrollTop: '+scrollTop);
      console.log('position: '+position);
      if (position) {
        document.querySelectorAll(this.target).forEach(element => {
          element.style.backgroundPosition = 'center top -' + position + 'px';
        });
      }
    });
  }
}

document.addEventListener('DOMContentLoaded', event => {
  new ParallaxEffectBackground();
});
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.