2013-11-28 60 views
0

当当前窗口滚动高度低于或高于用户滚动到的当前页面时,我试图将<div>元素附加到我的容器中。在下面的标记:滚动时附加div元素

<div id="st-container" class="st-container"> 
     <div class=" fullscreen-container animated fadeInDown" id="fullscreen-container"> 
      <div class=" custom_inner offset2" id="fullscreen"> 
       <div class="pageHolder" id="3"> 
       </div> 
       <div class="pageHolder" id="4"> 
       </div> 
      </div> 
     </div> 
    </div> 

<div>元素我跟工作人员有类pageHolder,在$(window).scroll()功能,我想获得当前页面持有人的高度和附加的顶部或底部,取决于用户如何滚动,如果该元素不存在,则为新的div元素,如果我无法通过id找到它,则元素不存在。我已经试过这到目前为止,但不确定从哪里去:

$(window).scroll(function() { 
    var scrollTop = $(this).scrollTop(); 
    $('.pageHolder').each(function(){ 
     var position = $(this).position(); 
    }) 
} 

回答

0

不太清楚,如果这正是你希望做的,因为我是一个有点糊涂了你的解释,但我想我给它一个镜头:D

$(window).scroll(function(){ 
    var scrollTop = $(this).scrollTop(); 

    $('.pageHolder').each(function(){ 
     var $this = $(this), 
      position = $this.position(), 
      id = parseInt($this.attr('id')), 
      $div = $('<div>'); 

     if(scrollTop > position.top){ 
      /* 
      If window scrollTop is greater that its top position 
      check if the immediate succeeding sibling exist 
      */ 
      if(!$this.next('.pageHolder').length){ 
       /* 
       If its next sibling does not exist 
       create a new sibling <div> by inserting it after this 'pageHolder' 
       */ 
       $div.addClass('pageHolder').attr('id',id+1).text('pageHolder id'+(id+1)); 
       $this.after($div) 
      }   
     }else{ 
      if(!$this.prev('.pageHolder').length){ 
       $div.addClass('pageHolder').attr('id',id-1).text('pageHolder id'+(id-1)); 
       $this.before($div) 
      } 
     } 
    }); 

    /* 
    Make a continouos scroll when scrolling up 
    Without this set of code, prepending a new <div> is not possible 
    */ 
    if(scrollTop == 0){ 
     $(window).scrollTop(50); 
    } 

}).scrollTop(50); //Make the window start with a scrollTop of 50, this is essential for the continouos scrolling up 

检查这个fiddle

+0

这让我开始了正确的道路。 – Warz