mat*_*att 111 javascript position offset zepto
我习惯使用jQuery.在我目前的项目中,我使用zepto.js.Zepto没有position()像jQuery那样提供方法.Zepto只附带offset().
知道如何使用纯js或Zepto检索容器相对于父级的偏移量吗?
jac*_*ers 184
element.offsetLeft并且element.offsetTop是用于查找元素相对于其位置的纯javascript属性offsetParent; 是最近的父元素,其位置为relative或absolute
或者,您始终可以使用Zepto来获取元素及其父元素的位置,并简单地减去这两个元素:
var childPos = obj.offset();
var parentPos = obj.parent().offset();
var childOffset = {
top: childPos.top - parentPos.top,
left: childPos.left - parentPos.left
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,即使未定位父项,也可以为子项提供相对于其父项的偏移量.
fca*_*ran 54
在纯js中只是使用offsetLeft和offsetTop属性.
示例小提琴:http://jsfiddle.net/WKZ8P/
var elm = document.querySelector('span');
console.log(elm.offsetLeft, elm.offsetTop);Run Code Online (Sandbox Code Playgroud)
p { position:relative; left:10px; top:85px; border:1px solid blue; }
span{ position:relative; left:30px; top:35px; border:1px solid red; }Run Code Online (Sandbox Code Playgroud)
<p>
<span>paragraph</span>
</p>Run Code Online (Sandbox Code Playgroud)
小智 5
我是在Internet Explorer中这样做的。
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;
};
Run Code Online (Sandbox Code Playgroud)
===================你可以这样称呼它
getWindowRelativeOffset(top, inputElement);
Run Code Online (Sandbox Code Playgroud)
我只关注IE,但是其他浏览器也可以做类似的事情。
我得到了另一个解决方案。从子属性值中减去父属性值
$('child-div').offset().top - $('parent-div').offset().top;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
214859 次 |
| 最近记录: |