高级Jquery |滚动选择的导航 [英] Advanced Jquery | Scroll Nav Selected

查看:57
本文介绍了高级Jquery |滚动选择的导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户滚动到页面上的特定部分时,我需要选择li元素的帮助:

I need help with selecting a li element when a user scrolls to a particular section on a page:

查看我的进度: http://jsfiddle.net/FvBqA/349/

如果您单击服务"链接,则文字颜色应变为页面该部分的红色,如果您单击家庭"或联系人",则文字颜色也将再次变为红色.

If you click on the "services" link the text color should change to red as you are on that section of the page, same again if you were to click on "home" or "contact".

我对jquery有一个想法,那就是您需要能够向LI添加和删除类,以便css可以选择所选的类并按照其进行渲染.

I have an idea regarding the jquery is that you'd need to be able to add and remove classes to the LI so that the css can pick up the selected class and render as per.

可以在此处查看该功能: http://demicreative.com/#capabilities

The functionality can be viewed here: http://demicreative.com/#capabilities

如果向下滚动并查看工作部分,您会注意到导航项已被选择-我具有相同的功能.

If you scroll down and see the work section you will notice the nav item is selected - I am after the same functionality.

推荐答案

尝试一下:

var header_height = $('#nav').outerHeight();
var sections = [];
$('#nav a').each(function(){    
    var section = $(this.hash).offset()
    sections.push({
        'link':$(this).parent(),
        'top' : $(this.hash).offset().top-header_height,
        'bottom' : $(this.hash).offset().top + $(this.hash).outerHeight() -header_height
    });
});

$('#nav a').click(function(e) {
    e.preventDefault();
    $('html,body').animate({
        scrollTop: $(this.hash).offset().top - header_height
    }, 500);
});


$(window).scroll(function(){   
    for(var i = 0; i < sections.length; i++)
        if($(window).scrollTop() >= sections[i].top &&
           $(window).scrollTop() <= sections[i].bottom){
            sections[i].link.addClass('selected')
                .siblings().removeClass('selected');
        }
});​

我将事件直接附加到#nav中的链接.我将选定的类添加到父元素,并将其从父元素的兄弟姐妹中删除.我还使滚动偏移量减少了70像素,即导航栏的高度及其填充.

I attached the event directly to links in the #nav. I add the selected class to the parent element and remove the it from the parent element's siblings. I also make the scroll offset 70 px less, the height of the nav and it's padding.

已更新:仅对特定部分没有参考,这意味着如果您展开,添加新链接或部分,则无需更新JavaScript即可继续使用.

Updated: There is no reference to any particular section only sections this means if you expand, adding new links or sections it will still work without having to updated the JavaScript.

提琴: http://jsfiddle.net/iambriansreed/5Ta8j/

这篇关于高级Jquery |滚动选择的导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆