2010-09-03 91 views
1

我有一个DIV我想滚动页面,但它不可见以上的折叠,所以我用这个。使用.offset()。顶部找到页面上的元素位置

$(window).scroll(function() { 
    // Get scrolling position of document 
    var scrollYpos = $(document).scrollTop(); 

    // if its more than the top of the element 
    if (scrollYpos > 551) { 

     // Add a margin to the top 
     $('#scrollingDiv').animate({'margin-top': scrollYpos - 541 }, {duration: 300, queue: false}); 
    } else { 
     $('#scrollingDiv').animate({'margin-top': 0 }, {duration: 200, queue: false}); 
    }}); // end scroll 

ATM我手动给它垂直位置的DIV(551px)。我想动态地做到这一点。

var elYpos = $('#scrollingDiv').offset().top 

因此,这将找到该元素在页面上的垂直位置,但是当元素移动时,这个改变将螺丝钉固定起来。

如何获取元素的位置一次?

回答

6

在函数前面定义了你的变量,所以它只取一次。

$(function(){ 
    var elYpos = $('#scrollingDiv').offset().top; // elYpos variable will stay as it's defined 
    $(window).scroll(function(){ 
    var scrollYpos = $(document).scrollTop(); 
    if (scrollYpos > elYpos) { 
    // and rest of tour code... 
    }); 
}); 
+0

太棒了,谢谢 – Reynish 2010-09-03 10:53:01

相关问题