2013-07-03 65 views
0

我正在嘗試使頁面上的某個元素向下滾動到頁面上,當您向下滾動到某個點時。當它移動的另一個元素擊中它時,我將它切換到position: fixed。問題是,當它切換到position: fixed時,它會沿頁面向下移動大約四分之一,因爲這是它在頁面上的原始位置。有什麼方法可以使用它在切換到固定位置時的位置,而不是讓它跳到原來的位置?當切換到固定位置時使用新位置

下面是一些代碼:

jQuery(window).scroll(function (event) { 
    var top = jQuery("accordion").offset().top - parseFloat(jQuery("#accordion").css("marginTop").replace(/auto/, 0)); 
    // what the y position of the scroll is 
    var y = jQuery("#navigation").offset().top + jQuery("#navigation").height(); 

    // whether that's below the form 
    if (y >= top) { 
     // if so, ad the fixed class 
     jQuery("#accordion").css('position','fixed'); 
    } else { 
      // otherwise remove it 
      jQuery("#options_accordion").css('position', ''); 
     } 
}); 

回答

1

您需要設置粘元素的頂部位置,在你切換到位置的連接點:固定的。我創建了一個簡單的例子向你展示我的意思:

http://jsfiddle.net/BSpyM/

var $sticky = $('.sticky'); 
var $win = $(window); 
var originalStickyPosition = $sticky.offset().top; 

// Change this if you want it to switch at some point other 
// than the top of the window 
var switchPoint = 0; 

$win.on('scroll', function (event) { 
    var scrollTop = $win.scrollTop(); 

    if ((originalStickyPosition - scrollTop) <= switchPoint) { 
     if (!$sticky.hasClass('stuck')) { 
      $sticky.css('top', switchPoint); 
      $sticky.css('left', $sticky.offset().left); 
      $sticky.addClass('stuck'); 
     } 
    } else { 
     if ($sticky.hasClass('stuck')) { 
      $sticky.removeClass('stuck'); 
     } 
    } 
});