3

I need a bit of advice as I can't get my noob head around the following, please see this fiddle: http://jsfiddle.net/NtUpw/

The code works as intended, but when the current div offset goes > 41 and prev is hit, I'd like the page to return to the beginning of the current div, not to one before that. Any idea how can I add this condition?

I realise the current code isn't the cleanest (actually it's a combination of two fiddles), but I hope someone could take a look at it anyway. Thanks.

$('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');
        }
    });
});
4

1 回答 1

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
    });

有了这个,导航器只有在不在当前的顶部时才会跳转到前一个 div;或者跳到上一个。

Firefox 问题取决于 Firefox 如何放置溢出,它将溢出放置在与其他浏览器不同的html级别。body为了让它工作,你必须定义滚动动作:

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

});

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

于 2013-04-21T15:04:38.947 回答