2012-06-06 78 views
2

我试图复制类似于this的内容。在某个点停止滚动

当你向下滚动,你(position: fixed)在div滚动,直到它到达某一点,在那里不动为止(position: absolute),和你继续向下滚动,它保留了页(250px)上的位置,直到你卷起来再次拾起它。

What I have so far

现在我的小提琴会做所有事情,除非它不保留它被“脱落”的位置,而是回到原来的位置。

想法?

回答

1

您需要计算窗口的scrollTop值,然后将其应用为top和set position的值为absolute。

$('element').css({ 
    'top': $(window).scrollTop(), 
    'position': 'absolute' 
}); 

当你继续滚动,虽然scrollTop值会改变,所以你只能这样做一次。 。使用一个变量来跟踪什么状态元素是据我所知,有三种:

  1. 相对
  2. 固定
  3. 绝对

有了这个变量,你还可以通过在需要时设置类来减轻浏览器的压力。例如:

if(y > 100 && pos != 'fixed'){ 

    pos = 'fixed'; 

    $('element').addClass('fixed'); 

}else if(y > 100 && pos != 'relative'){ 

    pos = 'relative'; 

    $('element').addClass('relative'); 

} 

希望帮助:)

0

我做了以下变化:

if (y >= socialTop & y <= 150) { 
    $('#static-social').addClass('fixed'); 
} else { 
    $('#static-social').removeClass('fixed'); 
} 

要:

if (y >= socialTop & y <= 150) { 
    $('#static-social').css('marginTop', $(this).scrollTop()); 
} 

这确保了元件停留在基于窗口的位置在页面的顶部,所以当你向后滚动它的位置。

+0

这是一个做事的非常缓慢,集约化的方式。你基本上取代了浏览器的原生位置:使用javascript修复了各种功能。当我们不得不为ie6做这件事时提醒我。 – will