2015-05-04 94 views
3

我ClientRect對象的數組,我得到了做查找最接近BoundingClientRect

var trackedElements = $('[track]'); 
var trackedBounds = []; 
_.each(trackedBounds, function(elem) { 
    return $(elem)[0].getBoundingClientRect(); 
}); 

什麼我也有另一種元素的邊界客戶矩形。

var currentElement = $('.active')[0].getBoundingClientRect();

我的問題是,我該如何找到內trackedBoundscurrentElement最接近北?

回答

0

我想你可以過濾不在北currentElement rects:

trackedBounds = trackedBounds.filter(rect => rect.bottom > currentElement.top) 
他們 .bottom財產

和排序剩餘rects:

trackedBounds = trackedBounds.sort((rect1, rect2) => rect1.bottom - rect2.bottom) 

結果是trackedBounds數組的第一個元素:

let result = trackedBounds 
    .filter(rect => rect.bottom > currentElement.top) 
    .sort((rect1, rect2) => rect1.bottom - rect2.bottom) 
    [0]