LoginSignup
6

More than 3 years have passed since last update.

windowスクロール量の「累計値」を取得する

Last updated at Posted at 2015-06-03

単純な「windowのスクロール量(scrollTop値)」ではなく、上下スクロール量の「累計値」を取得する方法を考えてみます。

スクロールの上下方向にかかわらず「スクロールによる移動量をひたすら加算し続ける」というイメージです。

実装結果とソースコード抜粋

See the Pen qiita_6bef19395077f427111c by Sho Uchida (@shouchida) on CodePen.

JavaScript
// jQuery使用

var $window = $(window);

// 上下スクロール量を累計
var sumScroll = {
    currentScrollTop: 0,
    diffScrollTop: 0,
    sumScrollValue: 0,

    // 初期化
    init: function() {
        var self = this;
        this.currentScrollTop = $window.scrollTop();
        $window.on('scroll', function() {
            self.update();
        });
    },

    // 更新
    update: function() {
        var scrollTop = $window.scrollTop();
        if (scrollTop === this.currentScrollTop) {
            return;
        }
        this.diffScrollTop = Math.abs(this.currentScrollTop - scrollTop);
        this.currentScrollTop = scrollTop;
        this.sumScrollValue += this.diffScrollTop;

        doSomething(this.sumScrollValue);
    }
};

// 上下スクロール量の累計値を利用した何らかの処理
function doSomething(value) {
    console.log(value);
}

$window.on('load', function() {
    sumScroll.init();
});

scrollイベントが発生するたびに、「直前のscrollTop値」と「現在のscrollTop値」を比較し、その差分を加算し続けます。

「2000px分スクロールするごとに画面内の表示が切り替わる」
といった演出に利用できそうです。

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
6