当切换到固定位置时使用新位置
问题描述:
我正在尝试使页面上的某个元素向下滚动到页面上,当您向下滚动到某个点时。当它移动的另一个元素击中它时,我将它切换到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', '');
}
});
答
您需要设置粘元素的顶部位置,在你切换到位置的连接点:固定的。我创建了一个简单的例子向你展示我的意思:
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');
}
}
});