我正在寻找一种方法来告诉窗口顶部的距离,如果用户进行滚动,则使用jQuery更改css。我尝试过这样的事情并不起作用:
var topDistance = $('div').offset().top; // distance of the div relative to the top of the window
$('div').css({position: 'absolute',top:topDistance, right:'0px'});
有没有办法将变量放在jQuery css的“top”属性中?我尝试了上面的代码,它似乎不起作用。有谁知道如何改进代码?
答案 0 :(得分:3)
您可以使用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'});
}
}