2013-11-03 89 views
3

我已经在div中创建了一个div,我希望内部div在滚动页面上下浮动外部div内上下移动。我不知何故设法限制它不会离开外部div格式,但是当涉及到底部时,它会下降到页面底部。请帮帮我,这里是我的代码 CSS浮动一个div内的div向上滚动(而不是整个屏幕)

CSS

#comment { 
    position: absolute; 
    /* just used to show how to include the margin in the effect */ 
} 

HTML

<!--the outer div in which i have whole content --> 
<div class="content"> 
    <!--the floating div, remains well inside form top but moves down outside div from bottom --> 
    <div class="ftwrapper" id="comment">    
    </div><!--fb/twitter ends--> 
</div> 

JQuery的

$(function() { 
     var msie6 = $.browser == 'msie' && $.browser.version < 7; 
     if (!msie6) { 
      var top = $('#comment').offset().top - parseFloat($('#comment').css('margin-top').replace(/auto/, 0)); 
      $(window).scroll(function (event) { 
       // what the y position of the scroll is 
       var y = $(this).scrollTop(); 

       // whether that's below the form 
       if (y >= top) { 
        // if so, ad the fixed class 
        $('#comment').addClass('fixed'); 
       } else { 
        // otherwise remove it 
        $('#comment').removeClass('fixed'); 
       } 
      }); 
     } 
    }); 
+0

这听起来像你想要的东西,如[StickyFloat(http://dropthebit.com/demos/stickyfloat/stickyfloat.html)? –

+0

见www.webabinc.com/test,你会看到一个右侧的div,很好地浮动,但问题是我想限制它在外部div,内容div,但是当我添加页脚在底部时,它也会覆盖该页脚 – user2949898

+0

您基本上需要将其保留在容器内,而不是翻过页脚等等。 –

回答

1

我根据您的要求做了一个样本测试。 如果滚动速度太快,它就不能很好地工作,但否则就OK了。我稍后会对它进行一些更改。

var prevScroll = 0; 
$(window).unbind("scroll"); 
function reposition() { 
    var contPos = $("#container").offset(); 
    var comment = $('#comment');  
    contPos.bottom = contPos.top + $("#container").outerHeight(); 
    console.log('contPos',contPos); 
    $(window).scroll(function (event) { 
     // what the y position of the scroll is 
     var  scroll = $(window).scrollTop() 
      , y = scroll 
      , pos = comment.offset() 
     ; 
     pos.bottom = comment.outerHeight(); 
     if (scroll > prevScroll) { 
      //down 
     } else { 
      //up 
     } 
     prevScroll = scroll; 
     // whether that's below the form 
     console.log(pos.bottom + scroll ,":", contPos.bottom); 
     if (contPos.top > scroll) { 
      // if so, ad the fixed class 
      comment.css({ 
       position: 'relative', 
       bottom : '0px', 
       left : '0px' 
      }); 
      console.log("Too High"); 
     } else if (pos.bottom + scroll > contPos.bottom) { 
      //comment.removeClass('fixed'); 
      comment.css({ 
       position: 'absolute', 
       top  : (contPos.bottom - comment.outerHeight())+'px', 
       left  : pos.left+'px' 
      }); 

      console.log("Too Low"); 
     } else { 
      // middle area 
      console.log("Perfect"); 
      comment.css({ 
       position: 'fixed', 
       top : '0px', 
       left : pos.left + 'px' 
      }); 
     } 
    }); 
} 
$(document).ready(reposition); 

Jsfiddle test