使用jQuery获取元素相对于视口的位置


117

获取页面上元素相对于视口(而不是文档)的位置的正确方法是什么?jQuery.offset功能似乎很有希望:

获取第一个元素的当前坐标,或设置匹配元素集中相对于文档的每个元素的坐标。

但这与文档有关。是否有等效的方法返回相对于视口的偏移量?


5
注意:请参阅@Igor G的答案...
卡尔·史密斯

3
对于DA,您确实应该将Igor G的答案设置为可接受,这可以节省生命!
文森特·杜普雷兹

Answers:



287

确定元素的大小和位置的最简单方法是调用其 getBoundingClientRect()方法。此方法返回视口坐标中的元素位置。它不包含任何参数,并返回一个对象,其属性为left,right,topbottom。left和top属性给出元素左上角的X和Y坐标,right和bottom属性给出元素右下角的坐标。

element.getBoundingClientRect(); // Get position in viewport coordinates

支持无处不在。


15
令人难以置信的是,这种方法是由IE5添加的……如果情况良好,那就太好了!
罗伊·里奥哈斯(Roy Riojas)2013年

这起初似乎很大,但它没有考虑在移动Safari用户缩放7
MyNameIsKo

2
最新的firefox不支持getBoundingClientRect is not a function
user007 2014年

2
@ user007我确认最新的Firefox支持它。
2014年

26
好的答案,并使其成为jquery就是这样:($('#myElement')[0].getBoundingClientRect().top或任何其他位置)
Guillaume Arluison 2015年

40

这是两个无需使用(膨胀的)尺寸插件即可获取页面高度和滚动量(x,y)的函数:

// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
    var windowHeight
    if (self.innerHeight) { // all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
}

太好了 很有用。
吉米2010年

出于好奇,在这种情况下,为什么要使用“ self”属性而不是window?
dkugappi 2012年


23

jQuery.offset需要与结合使用scrollTopscrollLeft如下图所示:

视口滚动和元素偏移

演示:

function getViewportOffset($e) {
  var $window = $(window),
    scrollLeft = $window.scrollLeft(),
    scrollTop = $window.scrollTop(),
    offset = $e.offset(),
    rect1 = { x1: scrollLeft, y1: scrollTop, x2: scrollLeft + $window.width(), y2: scrollTop + $window.height() },
    rect2 = { x1: offset.left, y1: offset.top, x2: offset.left + $e.width(), y2: offset.top + $e.height() };
  return {
    left: offset.left - scrollLeft,
    top: offset.top - scrollTop,
    insideViewport: rect1.x1 < rect2.x2 && rect1.x2 > rect2.x1 && rect1.y1 < rect2.y2 && rect1.y2 > rect2.y1
  };
}
$(window).on("load scroll resize", function() {
  var viewportOffset = getViewportOffset($("#element"));
  $("#log").text("left: " + viewportOffset.left + ", top: " + viewportOffset.top + ", insideViewport: " + viewportOffset.insideViewport);
});
body { margin: 0; padding: 0; width: 1600px; height: 2048px; background-color: #CCCCCC; }
#element { width: 384px; height: 384px; margin-top: 1088px; margin-left: 768px; background-color: #99CCFF; }
#log { position: fixed; left: 0; top: 0; font: medium monospace; background-color: #EEE8AA; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- scroll right and bottom to locate the blue square -->
<div id="element"></div>
<div id="log"></div>


2
这对我来说非常有用
约旦

无论如何,这绝对是正确的答案。所有的人都依赖于鼠标/滚动增量配置,浏览器,OBJ位置等问题
佩德罗·费雷拉

2

这是一个计算元素在视口中的当前位置的函数:

/**
 * Calculates the position of a given element within the viewport
 *
 * @param {string} obj jQuery object of the dom element to be monitored
 * @return {array} An array containing both X and Y positions as a number
 * ranging from 0 (under/right of viewport) to 1 (above/left of viewport)
 */
function visibility(obj) {
    var winw = jQuery(window).width(), winh = jQuery(window).height(),
        elw = obj.width(), elh = obj.height(),
        o = obj[0].getBoundingClientRect(),
        x1 = o.left - winw, x2 = o.left + elw,
        y1 = o.top - winh, y2 = o.top + elh;

    return [
        Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),
        Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))
    ];
}

返回值的计算如下:

用法:

visibility($('#example'));  // returns [0.3742887830933581, 0.6103752759381899]

演示:

function visibility(obj) {var winw = jQuery(window).width(),winh = jQuery(window).height(),elw = obj.width(),
    elh = obj.height(), o = obj[0].getBoundingClientRect(),x1 = o.left - winw, x2 = o.left + elw, y1 = o.top - winh, y2 = o.top + elh; return [Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))];
}
setInterval(function() {
  res = visibility($('#block'));
  $('#x').text(Math.round(res[0] * 100) + '%');
  $('#y').text(Math.round(res[1] * 100) + '%');
}, 100);
#block { width: 100px; height: 100px; border: 1px solid red; background: yellow; top: 50%; left: 50%; position: relative;
} #container { background: #EFF0F1; height: 950px; width: 1800px; margin-top: -40%; margin-left: -40%; overflow: scroll; position: relative;
} #res { position: fixed; top: 0; z-index: 2; font-family: Verdana; background: #c0c0c0; line-height: .1em; padding: 0 .5em; font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="res">
  <p>X: <span id="x"></span></p>
  <p>Y: <span id="y"></span></p>
</div>
<div id="container"><div id="block"></div></div>


0

我发现,截至2014年1月,cballou的答案在Firefox中不再起作用。特别是,if (self.pageYOffset)如果客户端向右滚动但没有向下滚动,则不会触发-因为这0是一个假数字。由于Firefox支持document.body.scrollLeft/ Top,因此一段时间未检测到此错误,但是它不再对我有效(在Firefox 26.0上)。

这是我修改后的解决方案:

var getPageScroll = function(document_el, window_el) {
  var xScroll = 0, yScroll = 0;
  if (window_el.pageYOffset !== undefined) {
    yScroll = window_el.pageYOffset;
    xScroll = window_el.pageXOffset;
  } else if (document_el.documentElement !== undefined && document_el.documentElement.scrollTop) {
    yScroll = document_el.documentElement.scrollTop;
    xScroll = document_el.documentElement.scrollLeft;
  } else if (document_el.body !== undefined) {// all other Explorers
    yScroll = document_el.body.scrollTop;
    xScroll = document_el.body.scrollLeft;
  }
  return [xScroll,yScroll];
};

经过测试并在FF26,Chrome 31,IE11中工作。几乎可以肯定的是,它们都适用于所有旧版本。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.