【问题标题】:jQuery get the location of an element relative to windowjQuery获取元素相对于窗口的位置
【发布时间】:2011-04-12 11:50:11
【问题描述】:

给定一个 HTML DOM ID,如何在 JavaScript/JQuery 中获取元素相对于窗口的位置?这与相对于文档或偏移父级不同,因为元素可能位于 iframe 或其他一些元素内。我需要获取当前显示的元素矩形的屏幕位置(如位置和尺寸)。如果元素当前不在屏幕上(已被滚动),则可以接受负值。

这适用于 iPad (WebKit / WebView) 应用程序。每当用户点击UIWebView 中的特殊链接时,我应该打开一个弹出视图,显示有关该链接的更多信息。弹出视图需要显示一个箭头,该箭头指向调用它的屏幕部分。

【问题讨论】:

    标签: javascript jquery ipad webkit webview


    【解决方案1】:

    最初,抓取元素的.offset 位置并计算它相对于窗口的相对位置

    参考
    1.offset
    2.scroll
    3.scrollTop

    你可以试试这个fiddle

    下面几行代码解释了如何解决这个问题

    .scroll事件执行时,我们计算元素相对于window对象的相对位置

    $(window).scroll(function () {
        console.log(eTop - $(window).scrollTop());
    });
    

    当在浏览器中进行滚动时,我们调用上面的事件处理函数

    代码 sn-p


    function log(txt) {
      $("#log").html("location : <b>" + txt + "</b> px")
    }
    
    $(function() {
      var eTop = $('#element').offset().top; //get the offset top of the element
      log(eTop - $(window).scrollTop()); //position of the ele w.r.t window
    
      $(window).scroll(function() { //when window is scrolled
        log(eTop - $(window).scrollTop());
      });
    });
    #element {
      margin: 140px;
      text-align: center;
      padding: 5px;
      width: 200px;
      height: 200px;
      border: 1px solid #0099f9;
      border-radius: 3px;
      background: #444;
      color: #0099d9;
      opacity: 0.6;
    }
    #log {
      position: fixed;
      top: 40px;
      left: 40px;
      color: #333;
    }
    #scroll {
      position: fixed;
      bottom: 10px;
      right: 10px;
      border: 1px solid #000;
      border-radius: 2px;
      padding: 5px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="log"></div>
    
    <div id="element">Hello
      <hr>World</div>
    <div id="scroll">Scroll Down</div>

    【讨论】:

    • 感谢脚本。这似乎适用于桌面,但不适用于 iPad。似乎 $(window).scrollTop() 和 $(window).scrollLeft() 在 iPad 中没有得到更新。你可以通过jsbin.com/ogiwu4/5试试我的版本
    • 它们不会在 iPad 上得到更新,因为窗口本身没有滚动——用户在窗口内滚动。无论如何,基本网站就是这种情况,不确定针对移动设备的网站,可能有更多选择。
    • 当一个元素在另一个可滚动元素中时,这应该会失败,例如。 G。 &lt;div&gt;。您只考虑文档滚动而不考虑其他元素滚动。
    【解决方案2】:

    试试边界框。很简单:

    var leftPos  = $("#element")[0].getBoundingClientRect().left   + $(window)['scrollLeft']();
    var rightPos = $("#element")[0].getBoundingClientRect().right  + $(window)['scrollLeft']();
    var topPos   = $("#element")[0].getBoundingClientRect().top    + $(window)['scrollTop']();
    var bottomPos= $("#element")[0].getBoundingClientRect().bottom + $(window)['scrollTop']();
    

    【讨论】:

    • getBoundingClientRect() 是这个问题的答案。谢谢你的程序。
    • 这很好用。除了你的scrollLetf和scrollTop之外,我只需要包含一些代码来修复我的滚动:topPos = topPos - $(window).scrollTop(); leftPos = leftPos - $(window).scrollLeft(); rightPos = rightPos - $(window).scrollTop(); bottomPos = bottomPos - $(window).scrollLeft();
    • 人们将学会用一种非常有用的方法来包装事物的那一天
    • @Noldorin 对 IE/Edge 的支持对我来说看起来不错:caniuse.com/#feat=getboundingclientrect
    • @prograhammer 我的错,你是对的。我在某个网站上读到了这篇文章,并从表面上理解了它的意思……结果证明这是错误的(或者至少在旧 IE 上不起作用)。
    【解决方案3】:
    function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
    
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
    
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
    
        return offset;
    };
    

    你可以这样称呼它

    getWindowRelativeOffset(top, inputElement);
    

    我只根据我的要求专注于 IE,但其他浏览器也可以这样做

    【讨论】:

      【解决方案4】:

      TL;DR

      headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();
      
      headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe
      

      .getBoundingClientRect() 似乎是 universal。从 jQuery 1.2 开始支持 .offset().scrollTop()。谢谢@user372551 和@prograhammer。要在 iframe 中使用 DOM,请参阅 @ImranAnsari's solution

      【讨论】:

        【解决方案5】:

        这听起来更像是您想要一个用于所选链接的工具提示。有很多 jQuery 工具提示,试试jQuery qTip。它有很多选择,并且很容易改变样式。

        否则,如果您想自己执行此操作,可以使用 jQuery .position()。有关.position() 的更多信息请访问http://api.jquery.com/position/

        $("#element").position(); 将返回元素相对于偏移父元素的当前位置。

        还有 jQuery .offset(); 将返回相对于文档的位置。

        【讨论】:

        • 它并不是真正的工具提示,而是打开一个原生 UI 小部件来添加注释。
        【解决方案6】:

        试试这个来获取一个元素相对于窗口的位置。

                $("button").click(function(){
                    var offset = $("#simplebox").offset();
                    alert("Current position of the box is: (left: " + offset.left + ", top: " + offset.top + ")");
                });
            #simplebox{
                width:150px;
                height:100px;
                background: #FBBC09;
                margin: 150px 100px;
            }
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <button type="button">Get Box Position</button>
            <p><strong>Note:</strong> Play with the value of margin property to see how the jQuery offest() method works.</p>
            <div id="simplebox"></div>

        查看更多@Get the position of an element relative to the document with jQuery

        【讨论】:

          【解决方案7】:
          function trbl(e, relative) {
              var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);
          
              return {
                  t : r.top    + relative['scrollTop'] (),
                  r : r.right  + relative['scrollLeft'](),
                  b : r.bottom + relative['scrollTop'] (),
                  l : r.left   + relative['scrollLeft']()
              }
          }
                  
          // Example
          trbl(e, window);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-12-17
            • 1970-01-01
            • 1970-01-01
            • 2013-04-25
            • 1970-01-01
            相关资源
            最近更新 更多