我想获得一个元素相对于浏览器的视口(显示页面的视口,而不是整个页面)的位置。如何在JavaScript中做到这一点?

非常感谢


当前回答

编辑:添加一些代码来处理页面滚动。

function findPos(id) {
    var node = document.getElementById(id);     
    var curtop = 0;
    var curtopscroll = 0;
    if (node.offsetParent) {
        do {
            curtop += node.offsetTop;
            curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
        } while (node = node.offsetParent);

        alert(curtop - curtopscroll);
    }
}

id参数是你想要偏移量的元素的id。改编自一个奇怪的帖子。

其他回答

var element =  document.querySelector('selector');
var bodyRect = document.body.getBoundingClientRect(),
    elemRect = element.getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top;
function inViewport(element) {
    let bounds = element.getBoundingClientRect();
    let viewWidth = document.documentElement.clientWidth;
    let viewHeight = document.documentElement.clientHeight;

    if (bounds['left'] < 0) return false;
    if (bounds['top'] < 0) return false;
    if (bounds['right'] > viewWidth) return false;
    if (bounds['bottom'] > viewHeight) return false;

    return true;
}

这里有一些关于Angular2 +的东西。在版本13上测试

event.srcElement.getBoundingClientRect().top;

根据德里克的回答。

/**
 * Gets element's x position relative to the visible viewport.
 */
function getAbsoluteOffsetLeft(el) {
  let offset = 0;
  let currentElement = el;

  while (currentElement !== null) {
    offset += currentElement.offsetLeft;
    offset -= currentElement.scrollLeft;
    currentElement = currentElement.offsetParent;
  }

  return offset;
}

/**
 * Gets element's y position relative to the visible viewport.
 */
function getAbsoluteOffsetTop(el) {
  let offset = 0;
  let currentElement = el;

  while (currentElement !== null) {
    offset += currentElement.offsetTop;
    offset -= currentElement.scrollTop;
    currentElement = currentElement.offsetParent;
  }

  return offset;
}

我假设在web页面中存在一个id为btn1的元素,并且包含jQuery。这适用于所有现代浏览器的Chrome, FireFox, IE >=9和Edge。 jQuery只是用来确定相对于文档的位置。

var screenRelativeTop =  $("#btn1").offset().top - (window.scrollY || 
                                            window.pageYOffset || document.body.scrollTop);

var screenRelativeLeft =  $("#btn1").offset().left - (window.scrollX ||
                                           window.pageXOffset || document.body.scrollLeft);