![](/img/trans.png)
[英]How to compare and filter two different JS objects that one to many relationship
[英]Compare the relationship of two objects with a third object
我正在尋找一種方法來查找兩個對象中哪個是與DOM樹順序(而不是像素)最接近的第三個對象。
相對於我希望與之比較的對象,這兩個需要比較的對象可以出現在DOM的任何位置。
假設對象是Node,那么您可以隨時使用
/*
compare each node in nodes to target. The node that's closest to target
will be returned. closest is defined as absolute x,y distance between
the top, left corner of two nodes
*/
function whichIsCloser(nodes, target) {
var rect = target.getBoundingClientRect()
return nodes.reduce(function (prev, current) {
var prevRect = prev.getBoundingClientRect(),
currentRect = current.getBoundingClientRect(),
prevDistance = Math.sqrt(
Math.pow(prevRect.left - rect.left, 2) +
Math.pow(prevRect.top - rect.top, 2)
),
currentDistance = Math.sqrt(
Math.pow(currentRect.left - rect.left, 2) +
Math.pow(currentRect.top - rect.top, 2)
)
return prevDistance < currentDistance ? prev : current
})
}
/*
compare nodes to target. The node that's closest to target will be returned
closest is defined as getting an array of all nodes in tree order and
returning the node who's index offset in the array wrt the target
is the smallest.
*/
function whichIsCloser(nodes, target) {
var allNodes = []
iterativelyWalk(document.documentElement.childNodes, function (node) {
allNodes.push(node)
})
return nodes.reduce(function (prev, current) {
var prevDistance = Math.abs(allNodes.indexOf(prev) - allNodes.indexOf(target)),
currentDistance = Math.abs(allNodes.indexOf(current) - allNodes.indexOf(target))
return prevDistance < currentDistance ? prev : current
})
}
我不確定我是否理解,但是您是指樹中它們之間的DOM元素之間的實際緊密度嗎?
如果是這樣,可以采取以下措施(可能不是最快的方法,但似乎可行):
var count = 1;
$('*').each(function() {
$(this).data('count', count);
count++;
});
var first = $("#firstobject").data('count'),
second = $("#secondobject").data('count'),
third = $("#thirdobject").data('count'),
tofirst = third>first ? third-first : Math.abs(third-first),
tosecond = third>second ? third-second : Math.abs(third-second);
if (tofirst<tosecond) {
alert('first is closer than second to third');
}else{
alert('second is closer than first to third');
}
這是一塊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.