Vue获取页面元素的相对位置的方法示例

2020-06-16 06:54:11易采站长站整理

console.log(top2)
console.log(top3)
this.scrollTop(top)
}

效果如下

总结三种方法获取元素距离文档顶部位置


dom.getBoundingClientRect().top + window.scrollY;
或者
dom.getBoundingClientRect().top+document.documentElement.scrollTop;
或者
function getElementTop(element){
  var actualTop = element.offsetTop;
  var current = element.offsetParent;

  while (current !== null){
     actualTop += current.offsetTop;
     current = current.offsetParent;
  }
  return actualTop;
}

参考文章

用Javascript获取页面元素的位置
获取元素距离页面顶部的距离