您可以使用offset()
从网页顶部获取偏移量的值。我用它来滚动菜单(当他们向下滚动页面时跟随用户)。
要更改 CSS,您需要使用scroll()
窗口上的事件。这是我用于在用户滚动时将元素(例如菜单)向下移动的代码。希望这会对您有所帮助:
var scrollTimer;
jQuery(document).ready(function($){
// this will set a callback on the scroll event for the window
$(window).scroll(function(e){
// i'm using a timer so that the menu "catches up" once the user has scrolled and finished scrolling
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function(){
scrollSidebar();
}, 200);
});
});
// this function will animate the object down
function scrollSidebar(){
// get the scroll location of the body
var scrollTop = $('body').scrollTop();
// offset of the menu I want to follow as you scroll
var offset = $('#scroll-menu').offset();
// get the margin-top to see if its already scrolled down at all
var margintop = $('#scroll-menu').css('margin-top');
// this just checks if the user has scrolled down so the top of the menu element is now off the screen (e.g. if they have scrolled too far then the menu should follow the scroll amount, if the top of the element is in view then it needs to revert to the top again)
if(scrollTop > (offset.top-parseInt(margintop))){
$('#scroll-menu').animate({'margin-top':(scrollTop-(offset.top-parseInt(margintop)))+'px'}, "fast"); // 20 px extra padding
}
else {
$('#scroll-menu').animate({'margin-top':'0px'});
}
}