็ถ่ฆ็ชๆฒๅๆ๏ผ
ไฝ Element ็ธๅฐๆผ document ็ๅบงๆจ (elem.page) ไธๆ่ฎใ
๐พ replit: elem.position()
โฌ๏ธ ้่ฆ๏ผ Vector, box models
// ๐ธ elem.position()
Element.prototype.position = function(coordSystem='document'){
// viewport to element = (x, y)
const {x, y} = this.getBoundingClientRect();
switch(coordSystem){
// relative to "viewport"
case 'viewport': return vec(x, y);
// relative to "document"
// document to viewport = (scrollX, scrollY)
default: return vec(scrollX + x, scrollY + y);
}
};
๐็ฏไพ๏ผ
// elements
const doc = document.documentElement; // <html> element
const info = $('#scrollInfo');
const span1 = $('#span1');
const coords = $('#pageCoords');
// scroll handler
window.onscroll = (event) => {
info.innerText = `viewport in page: ${viewport.positionInDocument}`;
coords.innerHTML = `
span in page: ${span1.position()}<br>
span in viewport: ${span1.position('viewport')}
`;
};