概要
JavaScriptでスクロール量を取得する簡易コードの個人的まとめです。
左からのスクロール量
var getScrollLeft = function(window) {
var pageXOffset = window.pageXOffset;
var document = window.document;
var body = document.body;
if (pageXOffset !== undefined) {
return pageXOffset;
}
/**
* @see https://dev.opera.com/articles/fixing-the-scrolltop-bug/
*/
var scrollingElement =
'scrollingElement' in document
? document.scrollingElement
: window.navigator.userAgent.indexOf('WebKit') != -1
? body
: document.documentElement || body.parentNode;
return scrollingElement.scrollLeft;
};
minify
var getScrollLeft=function(c){var d=c.pageXOffset,b=c.document,e=b.body;return void 0!==d?d:("scrollingElement"in b?b.scrollingElement:-1!=c.navigator.userAgent.indexOf("WebKit")?e:b.documentElement||e.parentNode).scrollLeft};
右からのスクロール量
var getScrollRight = function(window) {
var document = window.document;
var body = document.body;
var html = document.documentElement || body.parentNode;
/**
* @see https://dev.opera.com/articles/fixing-the-scrolltop-bug/
*/
var scrollingElement =
'scrollingElement' in document
? document.scrollingElement
: window.navigator.userAgent.indexOf('WebKit') != -1
? body
: html;
var maxScrollLeft = scrollingElement.scrollWidth - html.clientWidth;
return maxScrollLeft - getScrollLeft(window);
};
minify
var getScrollRight=function(c){var b=c.document,d=b.body,e=b.documentElement||d.parentNode;return("scrollingElement"in b?b.scrollingElement:-1!=c.navigator.userAgent.indexOf("WebKit")?d:e).scrollWidth-e.clientWidth-getScrollLeft(c)};
上からのスクロール量
var getScrollTop = function(window) {
var pageYOffset = window.pageYOffset;
var document = window.document;
var body = document.body;
if (pageYOffset !== undefined) {
return pageYOffset;
}
/**
* @see https://dev.opera.com/articles/fixing-the-scrolltop-bug/
*/
var scrollingElement =
'scrollingElement' in document
? document.scrollingElement
: window.navigator.userAgent.indexOf('WebKit') != -1
? body
: document.documentElement || body.parentNode;
return scrollingElement.scrollTop;
};
minify
var getScrollTop=function(c){var d=c.pageYOffset,b=c.document,e=b.body;return void 0!==d?d:("scrollingElement"in b?b.scrollingElement:-1!=c.navigator.userAgent.indexOf("WebKit")?e:b.documentElement||e.parentNode).scrollTop};
下からのスクロール量
var getScrollBottom = function(window) {
var document = window.document;
var body = document.body;
var html = document.documentElement || body.parentNode;
/**
* @see https://dev.opera.com/articles/fixing-the-scrolltop-bug/
*/
var scrollingElement =
'scrollingElement' in document
? document.scrollingElement
: window.navigator.userAgent.indexOf('WebKit') != -1
? body
: html;
var maxScrollTop = scrollingElement.scrollHeight - html.clientHeight;
return maxScrollTop - getScrollTop(window);
};
minify
var getScrollBottom=function(c){var b=c.document,d=b.body,e=b.documentElement||d.parentNode;return("scrollingElement"in b?b.scrollingElement:-1!=c.navigator.userAgent.indexOf("WebKit")?d:e).scrollHeight-e.clientHeight-getScrollTop(c)};