Skip to content

Instantly share code, notes, and snippets.

@naosim
Created March 31, 2018 02:18
Show Gist options
  • Save naosim/ca115f90a7f7c39c37b89fa85d66cd20 to your computer and use it in GitHub Desktop.
Save naosim/ca115f90a7f7c39c37b89fa85d66cd20 to your computer and use it in GitHub Desktop.
エレメントの位置を取得する
class DocumentTopPosition {
constructor(doc, win) {
this.document = doc || document;
this.window = win || window;
}
/**
* @returns {number} top position
*/
get(element) {
return this.window.pageYOffset + element.getBoundingClientRect().top;
}
/**
* @param {string} selector
* @returns {{element, top:number}} element and top position objects
*/
find(selector) {
const element = this.document.querySelector(selector);
if(!element) {
throw 'element not found'
}
return {element:element, top:this.get(element)};
}
/**
* @param {string} selector
* @returns {[{element, top:number}]} element and top position objects
*/
findAll(selector) {
var list = this.document.querySelectorAll(selector);
list.map = Array.prototype.map;
return list.map(v => ({element:v, top:this.get(v)}));
}
}
const documentTopPosition = new DocumentTopPosition();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment