📌  相关文章
📜  从顶部到元素的高度 - 无论代码示例

📅  最后修改于: 2022-03-11 15:00:40.533000             🧑  作者: Mango

代码示例1
window.addEventListener('load', function() {
  //get the element
  var elem = document.getElementById('test');
  //get the distance scrolled on body (by default can be changed)
  var distanceScrolled = document.body.scrollTop;
  //create viewport offset object
  var elemRect = elem.getBoundingClientRect();
  //get the offset from the element to the viewport
  var elemViewportOffset = elemRect.top;
  //add them together
  var totalOffset = distanceScrolled + elemViewportOffset;
  //log it, (look at the top of this example snippet)
  document.getElementById('log').innerHTML = totalOffset;
});