2013-11-03 90 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