将两个对象与第三个对象的关系进行比较
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');
}
这是一个FIDDLE
相关文章:
- 如何从类关系中检索对象列表
- 在Aurelia computeds中,当设置依赖关系时,如何声明对对象属性的依赖关系
- Angular 2,在没有直接关系的两个组件之间共享一个对象
- 经典方法的目的|与对象状态的关系
- 获取指向给定对象的所有解析关系
- 如何管理原始对象之间的数据依赖关系
- 嵌入多对多关系-如果一个新对象还不存在,则添加一个新的对象
- Javascript单元测试依赖关系-当依赖对象发生变化时,如何使测试失败
- 为什么没有将关系添加到模型中的 loopback.io 对象中
- 同一数组(AngularJS)中的javascript对象之间的一对一关系
- 在子对象中创建对父对象的引用是否会导致循环关系
- Parse.com 创建具有关系的对象
- Ember数据-类型错误:对象没有方法'每个关系'
- Parsejs angular/ionic在视图中检索关系对象(第二次打开页面时显示值)
- 将两个对象与第三个对象的关系进行比较
- 解析Javascript-如何通过关系对象进行查询's属性
- 在parse.com上的关系字段中重新查看对象
- Javascript对象关系
- 基于二进制映射的对象关系
- 猫鼬对象关系