element's top-left corner coordinates relative to the document page.
Last updated 1 year ago
🔰 JS ⟩ browser ⟩ DOM ⟩ types ⟩ Element ⟩ methods ⟩ .position()
box models
當視窗捲動時:
Element 的 .boundingBox 的位置座標 (.x, .y) 會變
viewport 的位置座標 (.scrollX, .scrollY) 會變
但 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')} `; };
viewport position relative to document coordinates.
.boundingBox of Element relative to viewport.
mouse event / touch event - .clientX, .clientY
JS.info ⟩ Getting document coordinates
Element ⟩ .getBoundingClientRect() ⟩ (.x, .y)
Window ⟩ (.scrollX, .scrollY)