比较使用 jquery 每个函数收集的数据

Compare data collected with jquery each function

我想要做的是比较每个元素的偏移量,并获得更接近 window 顶部的那个,然后对该特定元素做一些事情

$(".slide").each(function(index, el) {
   var $this = $(this);
   var offset = $this.offset().top - $(window).scrollTop();
});

所以基本上,如果我通过 console.log 打印偏移量并且每个元素都有 slide class、

我目前得到这些值:

slide1 = -875
slide2 = 250
slide2 = 850
slide4 = 1375

幻灯片 2 是当前最接近 0 的幻灯片,因此幻灯片 2 将是 div 我想做的事情...

希望我说得够清楚!

您离目标已经很近了

var found=null;
var found_top=0;
$(".slide").each(function(index, el) {
    var $this = $(this);
    var offset = $this.offset().top - $(window).scrollTop();
    if( ( found == null ) || ( ( offset >= 0 ) && ( offset < found_top ) ) ){
        found=this;
        found_top=offset:
    }
});
/** do something with found here **/