0

HTML:

<div class="find_div" id="some_id_1"></div>

<!-- other divs -->

<div class="find_div" id="some_id_2"></div>

    <!-- other divs -->


<div class="find_div" id="some_id_3"></div>

<!-- other divs -->

    <div class="target_div"></div>


<div class="find_div" id="some_id_4"></div>

<!-- other divs -->

<div class="find_div" id="some_id_5"></div>

    <!-- other divs -->


<div class="find_div" id="some_id_6"></div>

<!-- other divs -->

1)找到 find_div最接近的方法是target_div什么?

2)如何找到其他find_div不那么接近的 div ?

请注意,在所讨论的案例中没有祖先关系。因此,我认为 jaqueryclosest()在这里无效。

在我之前在这里提出了一个相关问题的问题后,我提出了这个问题。希望不要做任何重复。

编辑:在该行之前添加了几行代码target_div

4

3 回答 3

1

尝试.nextAll() - 抓取与给定选择器匹配的所有后续兄弟

$('.target_div').nextAll('.find_div').first();// gets closest one after

$('.target_div').nextAll('.find_div').eq(0) // <-- index of where they are in the collection

编辑

您将不得不对上一个和下一个 div 进行一些计算..并通过获取它们的位置来查看哪个更接近。

var $tdiv = $('.target_div');
var $prev = $tdiv.prevAll('.find_div').first();// prev .find_div div
var $nex = $tdiv.nextAll('.find_div').first();// next .find_div div
var closest;
// get distance between bottom of prev div and top of target div
var $prevDistance = $tdiv.position().top - ($prev.position().top + $prev.height());
// get distance between bottom of target div and top of next div
var $nexDistance = $nex.position().top - ($tdiv.position().top + $tdiv.height());

// if prev div distance is less than next div - closest == prev div
if ($prevDistance < $nexDistance) {
    closest = $prev;
} else {
    closest = $nex;
}
// now you can do whatver you want with the closest element
closest.dowhatever
// or if you want to do something to all others except closest
$('.find_div').not(closest).dowhatever

小提琴

于 2012-11-02T12:47:24.047 回答
0

您可以使用nextAll:

1)

$('.target_div').nextAll(".find_div").first()

2)

$('.target_div').nextAll(".find_div").not(':first')
于 2012-11-02T12:48:22.070 回答
0

由于任何横向 DOM 方法都有“单向方向”,因此您最好的选择似乎是从“body”标签元素开始,然后在 DOM 中下降以获取所有元素。这应该进行优化,但为了让您了解总体思路,请查看以下jsFiddle:(如果相等,则返回 2 个 DOM 元素)

 var domElems = $('body').find('*'),
    index = 0,
    targetIndex, prevIndex, nexttIndex, grabbedElems = [],
    results = [];

for (var i = 0, z = domElems.length; i < z; i++) {
    index++;
    if ($(domElems[i]).is('.find_div')) grabbedElems[index] = $(domElems[i]);
    else if ($(domElems[i]).is('.target_div')) targetIndex = index;
}

for (var i = 0, z = grabbedElems.length; i < z; i++) {
    if (grabbedElems[i]) {
        if (i < targetIndex) prevIndex = i;
        else if (i > targetIndex) {
            nextIndex = i;
            break;
        }
    }
}

if (Math.abs(prevIndex - targetIndex) <= Math.abs(nextIndex - targetIndex)) results.push(grabbedElems [prevIndex]);

if (Math.abs(nextIndex - targetIndex) <= Math.abs(prevIndex - targetIndex)) results.push(grabbedElems [nextIndex]);

if (results.length > 0) console.log(results[0]);
if (results.length > 1) console.log(results[1]);​
于 2012-11-02T14:11:50.677 回答