繁体   English   中英

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

[英]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
    })
}

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

这是一块

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM