获取元素相对于父容器的位置/偏移量? [英] Get position/offset of element relative to a parent container?

查看:4165
本文介绍了获取元素相对于父容器的位置/偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯使用jQuery。在我目前的项目中,我使用zepto.js。 Zepto不像jQuery那样提供 position()方法。 Zepto只附带 offset()

I'm used to working with jQuery. In my current project however I use zepto.js. Zepto doesn't provide a position() method like jQuery does. Zepto only comes with offset().

我知道如何检索容器相对于a的偏移量使用纯js或使用Zepto的父级?

Any idea how I can retrieve the offset of a container relative to a parent with pure js or with Zepto?

推荐答案

element.offsetLeft element.offsetTop 是纯javascript属性,用于查找元素相对于其 offsetParent 的位置;是最近的父元素,其位置为 relative 绝对值

element.offsetLeft and element.offsetTop are the pure javascript properties for finding an element's position with respect to its offsetParent; being the nearest parent element with a position of relative or absolute

或者,您可以随时使用 Zepto 获取元素及其父元素的位置,并简单地减去两者:

Alternatively, you can always use Zepto to get the position of an element AND its parent, and simply subtract the two:

var childPos = obj.offset();
var parentPos = obj.parent().offset();
var childOffset = {
    top: childPos.top - parentPos.top,
    left: childPos.left - parentPos.left
}

这样做的好处是可以为您提供相对于其父项的子项偏移量,即使父项未定位也是如此。

This has the benefit of giving you the offset of a child relative to its parent even if the parent isn't positioned.

这篇关于获取元素相对于父容器的位置/偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆