当您向下滚动到某个点时,我正在尝试在页面上向下滚动页面。当另一个移动的元素击中它时,我将它切换到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', '');
}
});
答案 0 :(得分:1)
您需要在将其切换到位置的位置设置粘性元素的顶部位置:固定。我已经创建了一个快速示例来向您展示我的意思:
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');
}
}
});