LoginSignup
6
5

More than 5 years have passed since last update.

windowとHTMLElementのスクロールの最大値を取得する

Last updated at Posted at 2016-12-09

それぞれscrollWidthとclientWidthとの差、scrollHeightとclientHeightとの差がスクロールの最大値となります。ここらへん古いブラウザではもうちょっと複雑だったけど今時のブラウザはこれで大丈夫だった。ただしiOS Safariでuser scaleを変化させるとずれます。

デモ

scrollMax.js
// windowなら
var winScrollMaxX = document.documentElement.scrollWidth - document.documentElement.clientWidth;
var winScrollMaxY = document.documentElement.scrollHeight - document.documentElement.clientHeight;

//scrollできる要素なら
var elemScrollMaxX = element.scrollWidth - element.clientWidth;
var elemScrollMaxY = element.scrollHeight - element.clientHeight;

Firefoxでは window.scrollMaxX, window.scrollMaxY というプロパティがあり、polyfillっぽく書くと

windowScrollMax-polyfill.js
// window.scrollMaxX, window.scrollMaxY polyfill
'scrollMaxX' in window || Object.defineProperties(window, {
    scrollMaxX: {
        enumerable: true,
        get: function(){
            return document.documentElement.scrollWidth - document.documentElement.clientWidth;
        },
    },
    scrollMaxY: {
        enumerable: true,
        get: function(){
            return document.documentElement.scrollHeight - document.documentElement.clientHeight;
        },
    }
});

HTMLElementにはFirefoxにもいないので、polyfillというかscrollMaxなプロパティを追加するなら

htmlElementScrollMax.js
// add scrollMaxX, scrollMaxY to HTMLElement
'scrollMaxX' in HTMLElement || Object.defineProperties(HTMLElement.prototype, {
    scrollMaxX: {
        enumerable: true,
        get: function(){
            return this.scrollWidth - this.clientWidth;
        },
    },
    scrollMaxY: {
        enumerable: true,
        get: function(){
            return this.scrollHeight - this.clientHeight;
        },
    }
});
6
5
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
6
5