使用Bootstrap ScrollSpy滚动至NEXT/PREV按钮

Scroll to NEXT/PREV buttons with Bootstrap ScrollSpy

本文关键字:PREV 按钮 NEXT Bootstrap ScrollSpy 滚动 使用      更新时间:2023-09-26

我一直在寻找创建下一个和上一个按钮的答案,这些按钮通过页面上的锚点,但找不到我需要的东西。这个可能接近我想要的,所以我决定把它作为一个起点:在不知道锚名称的情况下,我如何让链接指向页面上的下一个锚?

我对答案中的概念进行了修改,并试图使其与bootstrap的scrollspy(检测当前部分和锚点)一起工作。

我已经走到了这一步:http://jsfiddle.net/gukne0oL/2/

$('.next').click(function (e) {
    e.preventDefault();
    var current_anchor = $('li.active a');
    var next_anchor = current.next('li a');
    $('body').animate({
        scrollTop: next_anchor.offset().top
    });
})
$('.previous').click(function (e) {
    e.preventDefault();
    var current_anchor = $('li.active a');
    var previous_anchor = current.prev('li a');
    $('body').animate({
        scrollTop: previous_anchor.offset().top
    });
})

最初的答案针对<a>标签,但在bootstrap的scrollspy中,它将active类添加到包装<a>标签的<li>标签中。所以我相应地改变了它。。。我觉得很近?但我不知道。。。

有人能帮忙吗?非常感谢。

以活动li为目标,找到上一个/下一个li,并向下搜索到锚点。

http://jsfiddle.net/gukne0oL/9/

// Activate bootstrap scrollspy
$('body').scrollspy({ 
    target: '.navbar'
})
$('.next').click(function (e) {  
    var next = $('.navbar ul li.active').next().find('a').attr('href');
    $('html, body').animate({
        scrollTop: $(next).offset().top
    }, 500);
})
$('.previous').click(function (e) {
    var prev = $('.navbar ul li.active').prev().find('a').attr('href');
    $('html, body').animate({
        scrollTop: $(prev).offset().top
    }, 500);
})