当你向下滚动到某个点时,我正在尝试使我的页面上的元素与页面一起向下滚动。当另一个移动的元素命中它时,我让它切换到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', '');
}
});发布于 2013-07-04 01:27:00
您需要将粘性元素的顶部位置设置在将其切换为position: fixed的位置。我已经创建了一个快速示例来向您展示我的意思:
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');
}
}
});https://stackoverflow.com/questions/17451063
复制相似问题