简体   繁体   English

如何获取元素相对于浏览器视口的顶部 position?

[英]How to get an element's top position relative to the browser's viewport?

I want to get the position of an element relative to the browser's viewport (the viewport in which the page is displayed, not the whole page).我想获取相对于浏览器视口(显示页面的视口,而不是整个页面)的元素的 position。 How can this be done in JavaScript?如何在 JavaScript 中做到这一点?

Many thanks非常感谢

The existing answers are now outdated.现有的答案现在已经过时了。 The native getBoundingClientRect() method has been around for quite a while now, and does exactly what the question asks for.本机getBoundingClientRect()方法已经存在了很长时间,并且完全满足问题的要求。 Plus it is supported across all browsers (including IE 5, it seems!)此外,所有浏览器都支持它(似乎包括 IE 5!)

From MDN page :MDN 页面

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport .返回的值是一个 TextRectangle 对象,它包含描述边框的只读左、上、右和底部属性,以像素为单位,左上角相对于视口的左上角

You use it like so:你像这样使用它:

var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top = viewportOffset.top;
var left = viewportOffset.left;

On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:就我而言,为了安全起见,我将 window.scroll 添加到等式中:

var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;

That allows me to get the real relative position of element on document, even if it has been scrolled.这使我能够获得元素在文档上的真实相对位置,即使它已被滚动。

var element =  document.querySelector('selector');
var bodyRect = document.body.getBoundingClientRect(),
    elemRect = element.getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top;

Edit: Add some code to account for the page scrolling.编辑:添加一些代码来解释页面滚动。

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);
    }
}

The id argument is the id of the element whose offset you want. id 参数是您想要其偏移量的元素的 id。 Adapted from a quirksmode post .改编自quirksmode 帖子

jQuery implements this quite elegantly. jQuery 非常优雅地实现了这一点。 If you look at the source for jQuery's offset , you'll find this is basically how it's implemented:如果您查看 jQuery 的offset的源代码,您会发现这基本上是它的实现方式:

var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;

return {
    top: rect.top + win.pageYOffset,
    left: rect.left + win.pageXOffset
};
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;
}

source 来源

The function on this page will return a rectangle with the top, left, height and width co ordinates of a passed element relative to the browser view port. 页面上的函数将返回一个矩形,其中包含所传递元素相对于浏览器视口的顶部、左侧、高度和宽度坐标。

    localToGlobal: function( _el ) {
       var target = _el,
       target_width = target.offsetWidth,
       target_height = target.offsetHeight,
       target_left = target.offsetLeft,
       target_top = target.offsetTop,
       gleft = 0,
       gtop = 0,
       rect = {};

       var moonwalk = function( _parent ) {
        if (!!_parent) {
            gleft += _parent.offsetLeft;
            gtop += _parent.offsetTop;
            moonwalk( _parent.offsetParent );
        } else {
            return rect = {
            top: target.offsetTop + gtop,
            left: target.offsetLeft + gleft,
            bottom: (target.offsetTop + gtop) + target_height,
            right: (target.offsetLeft + gleft) + target_width
            };
        }
    };
        moonwalk( target.offsetParent );
        return rect;
}

You can try:你可以试试:

node.offsetTop - window.scrollY

It works on Opera with viewport meta tag defined.它适用于定义了视口元标记的 Opera。

Thanks for all the answers.感谢所有的答案。 It seems Prototype already has a function that does this (the page() function).似乎 Prototype 已经有一个函数可以做到这一点(page() 函数)。 By viewing the source code of the function, I found that it first calculates the element offset position relative to the page (ie the document top), then subtracts the scrollTop from that.通过查看该函数的源代码,我发现它首先计算元素相对于页面(即文档顶部)的偏移位置,然后从中减去scrollTop。 See the source code of prototype for more details.更多细节请参见原型的源代码。

I am assuming an element having an id of btn1 exists in the web page, and also that jQuery is included.我假设网页中存在一个 id 为btn1的元素,并且还包含 jQuery。 This has worked across all modern browsers of Chrome, FireFox, IE >=9 and Edge.这适用于 Chrome、FireFox、IE >=9 和 Edge 的所有现代浏览器。 jQuery is only being used to determine the position relative to document. 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);

Sometimes getBoundingClientRect() object's property value shows 0 for IE.有时,对于 IE, getBoundingClientRect()对象的属性值显示为 0。 In that case you have to set display = 'block' for the element.在这种情况下,您必须为元素设置display = 'block' You can use below code for all browser to get offset.您可以对所有浏览器使用以下代码来获取偏移量。

Extend jQuery functionality :扩展 jQuery 功能:

(function($) {
    jQuery.fn.weOffset = function () {
        var de = document.documentElement;
        $(this).css("display", "block");
        var box = $(this).get(0).getBoundingClientRect();
        var top = box.top + window.pageYOffset - de.clientTop;
        var left = box.left + window.pageXOffset - de.clientLeft;
        return { top: top, left: left };
    };
}(jQuery));

Use :采用 :

var elementOffset = $("#" + elementId).weOffset();

Based on Derek's answer.根据德里克的回答。

/**
 * Gets element's x position relative to the visible viewport.
 */
function getClientX(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 getClientY(el) {
  let offset = 0;
  let currentElement = el;

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

  return offset;
}

here is something for Angular2 +.这是Angular2 +的东西。 Tested on version 13在版本 13 上测试

event.srcElement.getBoundingClientRect().top;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取 iframe 相对于顶部窗口视口的位置? - How to get the position of an iframe relative to the top window's viewport? 获取相对于视口顶部的元素位置 - Get an element position relative to the top of the viewport 使用jquery获取元素相对于视口的位置 - Using jquery to get element's position relative to viewport 如何获得内部SVG元素相对于外部SVG元素视口的位置? - How do I get an internal SVG element's position relative to the viewport of an outer SVG element? 如何获取元素相对于broswer视口的位置 - How can I get the position of an element relative to the broswer viewport 获取子元素相对于侧视口的 position - Get position of child element relative to side viewport javascript:从浏览器的显示区域顶部获取元素的Y位置 - javascript: get element's Y position from top of the browser's display area 如何使用Google的Closure库获取DOM元素的当前视口位置? - How do you get the current viewport position of a DOM element using Google's Closure library? 相对于视口角度6的位置元素 - Position element relative to viewport angular 6 更改元素的“ offsetParent”以获取相对于其最接近的父元素的位置? - Change “offsetParent” of element to get position relative to it's closest parent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM