Javascript 如何找到元素与其父元素的“相对”位置?或者:如何找到蓝先生?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5324249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:41:04  来源:igfitidea点击:

How to find the 'relative' position of an element to its parent element? Or: How to find Mr. Blue?

javascriptjqueryhtml

提问by Kees C. Bakker

I have basically 2 div elements. The first is a scrolling container and the second one is an element that is placed in the container. I would like to find the y-position relative to the scrolling container. I wrapped all of it into a piece of example-code titled How to find Mr. Blue?

我基本上有 2 个 div 元素。第一个是滚动容器,第二个是放置在容器中的元素。我想找到相对于滚动容器的 y 位置。我将所有这些都打包成一段示例代码,标题为如何找到 Blue 先生?

<div style="height:100px; border:solid 1px black; overflow-y:scroll;">
    Please scroll down...
    <br/>
    <div style="height:400px;">
    </div>
    <br/>
    <div id="MrBlue" style="height:20px; background-color:blue; color:white">
        Mr. Blue
    </div>
</div>

So I would like a JavaScript / jQuery statementthat alerts the vertical-positionof the Mr. Blue. divrelativeto the scrolling container.

所以我想一个的JavaScript / jQuery的声明,提醒在垂直位置的的蓝先生。div对于滚动容器。

Ps. If you would like to 'fiddle' with mr. Blue, check http://jsfiddle.net/KeesCBakker/Qjr5q/.

附言。如果你想“摆弄”先生。蓝色,检查http://jsfiddle.net/KeesCBakker/Qjr5q/

回答by Tom Tu

If you can add css position: relativeto the wrapping/scrolling container then it's as simple as

如果您可以将 css 添加position: relative到包装/滚动容器,那么它就像

document.getElementById('MrBlue').offsetTop

and jsfiddle example http://jsfiddle.net/eU3pN/2/

和 jsfiddle 示例http://jsfiddle.net/eU3pN/2/

回答by felixsigl

you can use jQuery position

您可以使用jQuery 位置

$(document).ready(function() {
    alert($("#MrBlue").position().top);
});

see this jsfiddle

看到这个jsfiddle

Update:Container must have position:relative;otherwise it wont work

更新:容器必须有,position:relative;否则它将无法工作

see this updated jsfiddle

看到这个更新的jsfiddle

回答by Ionut Popa

Jquery's .position()

Jquery 的 .position()

The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.

Returns an object containing the properties top and left.

.position() 方法允许我们检索元素相对于偏移父元素的当前位置。将此与 .offset() 进行对比,后者检索相对于文档的当前位置。当将一个新元素放置在另一个元素附近并在同一个包含 DOM 元素中时, .position() 更有用。

返回一个包含 top 和 left 属性的对象。

http://jqapi.com/#p=position

http://jqapi.com/#p=position