Using jquery to get element's position relative to viewport

前端 未结 6 1237
囚心锁ツ
囚心锁ツ 2020-12-07 08:09

What\'s the proper way to get the position of an element on the page relative to the viewport (rather than the document). jQuery.offset function seemed promising:

6条回答
  •  既然无缘
    2020-12-07 08:42

    jQuery.offset needs to be combined with scrollTop and scrollLeft as shown in this diagram:

    viewport scroll and element offset

    Demo:

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

提交回复
热议问题