Shenglian / -WORK_TIP

工作上小技巧
4 stars 1 forks source link

[js] Get the position of an element relative to the document #137

Open Shenglian opened 6 years ago

Shenglian commented 6 years ago

function offset(el) {
  var rect = el.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
  }

  // example use
  var div = document.querySelector('div');
  var divOffset = offset(div);
  console.log(divOffset.left, divOffset.top);
}