2012-06-12 106 views
5

基本上我现在有一个div保持固定并跟随用户向下滚动,直到它达到某个点。我可以很容易地将它停在固定的像素位置,正如我在下面的示例中所做的那样,但是因为我是jQuery白痴,我不知道如何使它停止在div上。停止div滚动,一旦它达到另一个div

这是我到目前为止已经使用:

var windw = this; 

$.fn.followTo = function (pos) { 
    var $this = this, 
     $window = $(windw); 

$window.scroll(function(e){ 
    if ($window.scrollTop() > pos) { 
     $this.css({ 
      position: 'absolute', 
      top: pos 
     }); 
    } else { 
     $this.css({ 
      position: 'fixed', 
      top: 0 
     }); 
    } 
}); 
}; 

$('#one').followTo(400); 

这里的例子:jsFiddle

我希望它停止一旦达到第二个div的原因是因为与流体布局我使用时,第二个div将坐在不同的点上,这取决于浏览器的大小。为它定义一个特定的点将不起作用。任何人有任何想法,我怎么能得到这个做我想要的?或者,固定div有可能一旦达到下降百分比就停止滚动?我环顾四周,但还没有找到任何东西。

感谢您的任何帮助。

回答

8

这是你在找什么?

http://jsfiddle.net/Tgm6Y/1447/

var windw = this; 

$.fn.followTo = function (elem) { 
    var $this = this, 
     $window = $(windw), 
     $bumper = $(elem), 
     bumperPos = $bumper.offset().top, 
     thisHeight = $this.outerHeight(), 
     setPosition = function(){ 
      if ($window.scrollTop() > (bumperPos - thisHeight)) { 
       $this.css({ 
        position: 'absolute', 
        top: (bumperPos - thisHeight) 
       }); 
      } else { 
       $this.css({ 
        position: 'fixed', 
        top: 0 
       }); 
      } 
     }; 
    $window.resize(function() 
    { 
     bumperPos = pos.offset().top; 
     thisHeight = $this.outerHeight(); 
     setPosition(); 
    }); 
    $window.scroll(setPosition); 
    setPosition(); 
}; 

$('#one').followTo('#two'); 

编辑:关于你的请求不滚动,直到某一点,只需更换此:

if ($window.scrollTop() > (bumperPos - thisHeight)) { 

与此:

if ($window.scrollTop() <= (bumperPos - thisHeight)) { 
+1

好主,它的工作!现在去找出它为什么起作用。 MicronXD,你是一个绅士和学者,非常感谢你的可笑。 – mattmouth

+0

因为需要而提前道歉哈哈。是否有可能以某种方式将特定的代码添加到类似于此的东西 - http://jsfiddle.net/cpL69/13/ - 因为div在开始滚动之前不会开始滚动,然后在第二个div处结束它在你的例子中呢? – mattmouth

+0

将其添加到答案的末尾。 NP ...这就是我整天在做的事情......但是,不知怎的,我仍然因为做更多的事情而从赚取“无意义的互联网点”中获得乐趣。它可能更高效,但我很忙。我稍后会为你加紧。 – MicronXD

2

通过MicronXD的小提琴启发,但是当DOM在doc上受到大量推动时,写得更加灵活ument负载(或其他原因),这里是我为我自己的使用开发的另一个类似的解决方案:

jQuery.fn.extend({ 
    followTo: function (elem, marginTop) { 
    var $this = $(this); 
    var $initialOffset = $this.offset().top; 
    setPosition = function() { 
     if ($(window).scrollTop() > $initialOffset) { 
     if (elem.offset().top > ($(window).scrollTop() + $this.outerHeight() + marginTop)) { 
      $this.css({ position: 'fixed', top: marginTop }); 
     } 
     if (elem.offset().top <= ($(window).scrollTop() + $this.outerHeight() + marginTop)) { 
      $this.css({ position: 'absolute', top: elem.offset().top - $this.outerHeight() }); 
     } 
     } 
     if ($(window).scrollTop() <= $initialOffset) { 
     $this.css({ position: 'relative', top: 0 }); 
     } 
    } 
    $(window).resize(function(){ setPosition(); }); 
    $(window).scroll(function(){ setPosition(); }); 
    } 
}); 

然后你可以运行的功能,例如:

$('#div-to-move').followTo($('#div-to-stop-at'), 60); 

60是你想要的可选保证金浮动元素在位置上时从屏幕顶部具有:固定的,以像素表示。