使用JavaScript获取2个DOM元素之间的相对位置 [英] Get relative position between 2 DOM elements using JavaScript
问题描述
我已经实现了一组可以拖放的元素,可以使用jQuery把它们放到一些容器中。我需要的是将元素移动到特定容器而不进行用户交互的动画。问题在于,元素和下拉容器完全是DOM 的不同部分,并且大部分使用float定位。
I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely different parts of the DOM and mostly positioned using float.
我需要的只是一些代码获得2个浮动DOM元素之间的绝对位置差异,最好使用jQuery。我唯一发现的是一些hacks解析DOM,但总是非常浏览器特定的(例如这不适用于Firefox或IE或其他)。
All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever").
最好的是这样的:
var distance = getDistance(element1, element2);
或以jQuery表示法:
or in jQuery notation:
var distance = $(element1).distanceTo($(element2));
推荐答案
我从来没有使用jQuery,只是查找API,所以我可以假设你可以执行以下操作:
I never used jQuery, just looked up API, so I can assume you can do the following:
var o1 = $(element1).offset();
var o2 = $(element2).offset();
var dx = o1.left - o2.left;
var dy = o1.top - o2.top;
var distance = Math.sqrt(dx * dx + dy * dy);
这篇关于使用JavaScript获取2个DOM元素之间的相对位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!