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', '');
         }
});
4

1 回答 1

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');
        }
    }
});
于 2013-07-03T17:27:00.347 回答