Как узнать координаты определенного блока относительно всего документа при помощи JS
? Есть, конечно, методы getBoundingClientRect()
и getClientRect()
, но они определяют координаты относительно окна. Т.е. при скролле координаты меняются.
-
2Просто я тупой no comment :D– Randall29 окт 2018 в 19:25
2 ответа
Вы на правильном пути, для того, чтобы получить положение элемента относительно всего документа нужно знать положение элемента относительно окна и скролл страницы по осям (pageYOffset
и pageXOffset
).
Пример получения координат элемента относительно всей страницы:
function getCoords(elem) {
let box = elem.getBoundingClientRect();
return {
top: Math.round(box.top + pageYOffset),
left: Math.round(box.left + pageXOffset)
};
}
let testBlock = document.querySelector('.testBlock');
let counter = 0;
document.addEventListener("DOMContentLoaded", (e) => {
console.log('Страница загружена');
e.target.addEventListener("scroll", () => {
counter++;
console.log('Страница прокручена ' + counter + ' раз');
console.log('Top: ' + getCoords(testBlock).top);
console.log('Left: ' + getCoords(testBlock).left);
}, false);
}, false);
body {
margin: 0;
padding: 0;
}
.testBlock {
height: 200px;
width: 200%;
margin: 150px 10px 1000px;
border: 2px solid black;
}
<div class="testBlock">
</div>
Как видно из примера, положение элемента при скролле относительно всей страницы остается неизменным. Подробнее о работе с координатами можете прочитать здесь.
Подробно здесь: https://learn.javascript.ru/coordinates-document
let block = document.getElementById('block');
function getCoords(block) {
let box = block.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}
getCoords(block);
console.log(getCoords(block));
p {
width: 100px;
height: 100px;
border: 1px solid #000;
margin: 50px 0 0 150px;
}
<p id="block"></p>