2013-04-21 37 views
3

我需要一些建议,因为我不能让我围绕以下几个小白头,请参阅此琴:http://jsfiddle.net/NtUpw/jQuery的滚动当前位置和下一后退导航

的代码按预期工作,但是当当前div偏移量大于41并且prev被打中,我希望页面返回到当前div的开头,而不是之前的页面。任何想法如何添加此条件?我知道当前的代码不是最干净的(实际上它是两个小提琴的组合),但是我希望有人可以看看它。谢谢。

$('a.buttons').on('click', function (e) { 
e.preventDefault(); 

var t = $(this).text(), 
    that = $(this); 

if (t === 'next' && $('.current').next('div.post').length > 0) { 
    var $next = $('.current').next('.post'); 
    var top = $next.offset().top; 

    $('body').animate({ 
     scrollTop: $('.current').next('div.post').offset().top - 40 

    }); 

} else if (t === 'prev' && $('.current').prev('div.post').length > 0) { 
    var $prev = $('.current').prev('.post'); 
    var top = $prev.offset().top; 

    $('body').animate({ 
     scrollTop: $('.current').prev('div.post').offset().top - 40 
    }); 
} 



$(window).bind('scroll', function() { 
    $('.post').each(function() { 
     var post = $(this); 
     var position = post.position().top - $(window).scrollTop(); 

     if (position <= 40) { 

      post.addClass('current'); 
      post.prev().removeClass("current"); 

     } else { 
      post.removeClass('current'); 
     } 
    }); 
}); 
+1

这是奇怪的,它工作在Chrome,但不是FF。 – 2013-04-21 13:11:50

+0

就像这样:http://jsfiddle.net/IrvinDominin/2QYgR/1/? – 2013-04-21 13:37:59

+0

感谢您的快速回答!爱德华,你的调整就像一个魅力,除了第一个div。我也注意到FF问题,不知道可能会导致什么... – jonyjameson 2013-04-21 14:31:48

回答

2

prev操作通过将div始终移到前面;解决的办法是检查的导航尊重当前位置到当前的div:

var $prev; 
var top; 

var firstElem = true; 
if ($('.current').prev('div.post').length > 0) { 
    $prev = $('.current').prev('.post'); 
    top = $prev.offset().top; 
    firstElem = false 
} 

var currTop = $('.current').offset().top; 
var navBottom = $('.navigation').offset().top + 40; 

if (currTop == navBottom && !firstElem) { 
    $('body,html').animate({ 
     scrollTop: $('.current').prev('div.post').offset().top - 40 
    }); 

这个导航跳转到只有是不是在当前的顶部之前的股利;或者跳到上一个。

Firefox的问题取决于Firefox如何放置溢出,它像其他浏览器一样将其放置在html级别而不是body。 让它工作,你必须定义滚动操作:

$('body,html').animate({ 

}); 

工作小提琴:http://jsfiddle.net/IrvinDominin/2QYgR/3/

+1

再次,感谢您的伟大答案! – jonyjameson 2013-04-21 19:54:17

+0

@ jonyjameson欢迎您! – 2013-04-22 06:10:13

相关问题