在 window 滚动时面临滚动确切元素并将数据添加到 div 的问题

Facing issues to scroll exact element and add data to div on window scroll

有 1 个正在显示的主要部分和 4 个正在显示的空白部分 none。在滚动到 window 的底部时,它工作正常。当滚动到底部时,它是将数据添加到 div 并在滚动到底部时逐个显示块。但我想改变它。如果只有 main div 并且当用户滚动到 main div 时显示 #flash-sale 并且当用户滚动到 #flash-sale 时再次显示 #men-category 所以相同的过程对于所有 div。我的代码在 JSFiddle.

HTML

<div class="main" style="height:100px;background:#eee">Main</div>
<div style="height:100px;background:#eee;display:none" id="flash-sale"></div>
<div style="height:100px;background:#ccc;display:none" id="men-category"></div>
<div style="height:100px;background:#eee;display:none" id="women-category"></div>
<div style="height:100px;background:#ccc;display:none" id="all-products"></div>

jQuery

var pages = ["flash-sale","men-category","women-category","all-products"];
var count = 0;
var scrollFlag = true;
$(window).scroll(function(){
    if($(scrollFlag && window).scrollTop() == $(document).height() - $(window).height()){
        var name = pages[count];
        count++;
        if(count >= pages.length) scrollFlag = false;
        $("#"+name).append(name).css("display", "block");
    }
});

正在编辑代码并在此处遇到问题。当我更改代码 $(window).scrollTop() >= target 时,主 div 上的滚动到达位置不正确,并且一次滚动显示所有 divs。

var target = $(".main").offset().top;
var pages = ["flash-sale","men-category","women-category","all-products"];
var count = 0;
var scrollFlag = true;
$(window).scroll(function(){
    if(scrollFlag && $(window).scrollTop() >= target){
        var name = pages[count];
        count++;
        if(count >= pages.length) scrollFlag = false;
        $("#"+name).append(name).css("display", "block");
    }
});

我刚刚解决了这个问题,下面是新代码。也更新于 JSfiddle

var pages = ["flash-sale","men-category","women-category","all-products"];
var count = 0;
var scrollFlag = true;
$(window).scroll(function(){
    if(scrollFlag){
        if(count === 0){
            var target = $(".main").offset().top;
            var targetHeight = $(".main").outerHeight();
        }
        else
        {
            var target = $("#"+pages[count-1]).offset().top;
            var targetHeight = $("#"+pages[count-1]).outerHeight();
        }
        if($(window).scrollTop() > target - targetHeight){
            var name = pages[count];
            count++;
            if(count >= pages.length) scrollFlag = false;
            $("#"+name).append(name).css("display","block");
        }
    }
});