将两个对象与第三个对象的关系进行比较

Compare the relationship of two objects with a third object

本文关键字:对象 关系 比较 三个 两个      更新时间:2023-09-26

我正在寻找一种方法,根据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
    })
}

dom树位置

使用iterativelyWalk

/*
     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');
}​

这是一个FIDDLE