Created
March 31, 2018 02:18
-
-
Save naosim/ca115f90a7f7c39c37b89fa85d66cd20 to your computer and use it in GitHub Desktop.
エレメントの位置を取得する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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