3

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

我用该答案中提出的概念创建了一个小提琴,并试图使其与引导程序的 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>标签,但在引导程序的滚动间谍中,它将active类添加到<li>包装标签的<a>标签中。所以我相应地改变了它......我觉得它很接近?但我不能告诉...

任何人都可以帮忙吗?谢谢!

4

1 回答 1

3

定位活动 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);
})
于 2014-09-10T18:59:16.413 回答