1

我目前正在为这个开发网站构建一个滚动共享栏:http: //ossian.statenews.com/~matt/statenews-redesign-1.1/docs/article.html

如何让 jQuery 查找“相关故事”div 类并阻止它滚动过去?

这是我到目前为止所拥有的:

$(document).ready(function() {

var $sidebar   = $("#sharebox"),
$window    = $(window),
offset     = $sidebar.offset(),
topPadding = 50;

$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 0 

});
}
});
});
4

1 回答 1

2

所以基本上你只希望滚动分享栏在你向下滚动到那个低点时“粘”到相关的故事上。你已经成功了一半。与您在开始时不滚动共享栏的方式相同,与您在结束时停止滚动的方式相似。

您只需要确定何时要冻结滚动共享。

$(document).ready(function() {

  var $sidebar   = $("#sharebox"),
      $window    = $(window),
      offset     = $sidebar.offset(),
      topPadding = 50;

  $window.scroll(function() {
    if($window.scrollTop() > $('.related-stories').offset().top) {
      // basically this is just saying, that if you've scrolled passed the related
      // stories, we are going to force you back in line with them.
      // Edit: This needs to be first because the "else if" case is always true when
      //       this would be true so it never actually fails and calls this code.
      $sidebar.stop().css('marginTop', $('.related-stories').offset().top);
    } else if ($window.scrollTop() > offset.top) {
      $sidebar.stop().animate({
        marginTop: $window.scrollTop() - offset.top + topPadding
      });
    } else {
      $sidebar.stop().animate({
        marginTop: 0 
      });
    }
  });
});

This should solve the problem for you. The code might be a little off and you may need to play with it a bit. I'll check again if you have any follow up questions but that won't be until this evening. Good luck!

于 2012-08-23T19:38:19.360 回答