javascript - Récupérer la position (X,Y) d'un élément HTML

Mots clés : javascripthtmlcssdomposition

meilleur 5 Réponses javascript - Récupérer la position (X,Y) d'un élément HTML

vote vote

91

var rect = element.getBoundingClientRect(); console.log(rect.top, rect.right, rect.bottom, rect.left); 
var bodyRect = document.body.getBoundingClientRect(),     elemRect = element.getBoundingClientRect(),     offset   = elemRect.top - bodyRect.top;  alert('Element is ' + offset + ' vertical pixels from <body>'); 
vote vote

80

function getOffset( el ) {     var _x = 0;     var _y = 0;     while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {         _x += el.offsetLeft - el.scrollLeft;         _y += el.offsetTop - el.scrollTop;         el = el.offsetParent;     }     return { top: _y, left: _x }; } var x = getOffset( document.getElementById('yourElId') ).left;  
vote vote

72

function getOffset(el) {   const rect = el.getBoundingClientRect();   return {     left: rect.left + window.scrollX,     top: rect.top + window.scrollY   }; } 
getOffset(element).left 
getOffset(element).top 
vote vote

60

window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y  window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X 
vote vote

56

offsetLeft offsetTop 
clientLeft clientTop 

Questions similaires