【问题标题】:How to determine element coordinates in scrollable div?如何确定可滚动div中的元素坐标?
【发布时间】:2015-05-25 09:01:41
【问题描述】:

我有一个带有垂直滚动功能的div 元素。它有 span 元素,其中包含文本。我怎样才能得到这些span 元素的坐标。但我不希望它相对于滚动位置。

例如,在div 中,假设它的宽度为 400 像素,高度为 1000 像素(但视图高度为 500 像素),并且垂直滚动了一半。然后在视图的中心,我看到一个文本,如果我点击它,我想要像 (200, 250) 这样的坐标

如何获得div 容器的绝对坐标?

【问题讨论】:

    标签: javascript jquery html css scroll


    【解决方案1】:

    使用 element.getBoundingClientRect? (如果你想相对于容器减去容器的顶部。)

    function client() {
      alert(document.getElementById('child').getBoundingClientRect().top);
    }
    
    function local() {
      var container = document.getElementById('container');
      var containerRect = container.getBoundingClientRect();
      var child = document.getElementById('child');
      var childRect = child.getBoundingClientRect();
      localTop = childRect.top - containerRect.top;
      alert(localTop);
    }
    #container {
      height: 100px;
      overflow:scroll;
      border:1px solid red;
      margin-top:100px;
    }
    
    #child {
      background: yellow;
    }
    <div id="container">
      <div>Test</div>
      <div>Test</div><div>Test</div><div>Test</div><div>Test</div>
      <div id="child">Item of interest</div>
        <div>Test</div><div>Test</div><div>Test</div><div>Test</div>
    </div>
    <button onclick="client()">Global top</button>
    <button onclick="local()">Local top</button>

    【讨论】:

      【解决方案2】:

      假设可滚动 div 的 id 为“myDiv”,而 div 内的一个元素的 id 为“element1”。要在 javascript 中找到其真正的“顶级”值,请尝试以下操作:

      alert($('myDiv').css('top') + $('element1').css('top'));
      

      【讨论】:

        猜你喜欢
        • 2019-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多