提问人:Amir 提问时间:1/3/2021 更新时间:1/4/2021 访问量:89
面对滚动精确元素并在窗口滚动时向 div 添加数据的问题
Facing issues to scroll exact element and add data to div on window scroll
问:
有 1 个主要部分显示,4 个空部分不显示。滚动到窗口底部,它工作正常。滚动到底部时,它是将数据添加到div中,并在转到底部时一一显示块。但我想改变它。如果只有主 div,当用户滚动到达主 div 时,则显示 #flash-sale,当用户滚动到 #flash-sale 时再次显示 #men 类别,因此所有 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>
j查询
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");
}
});
编辑代码并在此处面对问题。当我更改代码时,主 div 上的滚动到达位置不正确,它在一个滚动中显示所有 div。$(window).scrollTop() >= target
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");
}
});
答:
0赞
Amir
1/4/2021
#1
我刚刚解决了这个问题,新代码如下。还在 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");
}
}
});
评论