jQuery根据部分的索引滚动到Sections

时间:2015-06-24 21:15:18

标签: javascript jquery html css

嗨,我希望我能够很好地解释这个问题。

我为页面创建了一个侧面导航,并创建了一个简单的jQuery脚本,根据页面上的部分数量动态添加按钮,这很有效。

所以我想要做的是,当单击导航栏上的链接时,它对应于该部分的索引并滚动到该部分。

例如,如果单击第二个链接,则转到第2部分。

已经很晚了,我可能会遗漏一些东西,但似乎无法将按钮(列表项)的索引传递给该部分的索引。

我可能会离家很远,所以要温柔,我第一次尝试过这样的事情。

jQuery(document).ready(function($) {
var $section = $('section').length;
var $nav = $('.side-navigation li').length;
//************************************************************************************//
//Dynamically add navigation buttons to side navigation dependant on number of sections
//************************************************************************************//
for(var i=0; i <= $section; i++);
$('section').each(function() {
    $('.side-navigation').append('<li><a href="#"></a></li>');
});
//************************************************************************************//
//Scrolls to section corresponding with the index of the link
//************************************************************************************//
$('.side-navigation li').click(function(){
        var index = $('.side-navigation li').index(this);
        console.log('this is index number' + " " + index);
        $('html, body').animate({
            scrollTop: $('section[i]').offset().top
        })
    });
//************************************************************************************//
//End
//************************************************************************************//

});

1 个答案:

答案 0 :(得分:0)

我现在已经解决了,可能不是最优雅的但是给了我一些工作:

这是我目前的解决方案:

    jQuery(document).ready(function($) {
var $section = $('section').length;
var $nav = $('.side-navigation li').length;
//************************************************************************************//
//Dynamically add navigation buttons to side navigation dependant on number of sections
//************************************************************************************//
$('section').each(function() {
    $('.side-navigation').append('<li><a href="#"></a></li>');
});
//**************************************************************************
//Dynamically add a unique class for each section for nav to target
//**************************************************************************
$('section').each(function(i) {
    $(this).addClass('section' + (i));
});
//************************************************************************************//
//Scrolls to section corresponding with the index of the link
//************************************************************************************//
$('.side-navigation li').click(function(){
        var index = $('.side-navigation li').index(this);
        $('html, body').animate({scrollTop: $('.section' + (index)).offset().top})
    });
//************************************************************************************//
//End
//************************************************************************************//
});