0

我正在寻找一种方法来判断与窗口顶部的距离,并在用户进行滚动时使用 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 的“顶部”属性中?我尝试了上面的代码,它似乎不起作用。有谁知道如何改进代码?

4

1 回答 1

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'});
    }
}
于 2012-09-21T14:01:52.560 回答