jquery - 单页网站上的事件 div 问题

标签 jquery css

我正在创建我的第一个单页网站。

这是一个 jsfiddle:http://jsfiddle.net/dgfhjxLt/

当您滚动浏览页面时,链接颜色应该会更改以向用户显示他们在该页面上,到目前为止这一切正常,问题出在第一个 div 上。

当您第一次访问该网站时,第一个链接应该显示为事件的,即文本应该是蓝色的,这不会发生,直到您先滚动一点然后它才能正常工作。

卡在了一个小时,确定这是一个简单的修复?

这是jquery:

jQuery(document).ready(function($) {   
var offsetHeader = 60;

$('.scroll').click(function(){
    var $target = $($(this).attr('href'));
    $(this).parent().addClass('active');
    $('body').stop().scrollTo( $target , 800, {'axis':'y', offset: -offsetHeader});
    return false;
});

/**
     * This part handles the highlighting functionality.
     * We use the scroll functionality again, some array creation and 
     * manipulation, class adding and class removing, and conditional testing
     */
    var aChildren = $("nav li").children(); // find the a children of the list items
    var aArray = []; // create the empty aArray
    for (var i=0; i < aChildren.length; i++) {    
        var aChild = aChildren[i];
        var ahref = $(aChild).attr('href');
        aArray.push(ahref);
    } // this for loop fills the aArray with attribute href values

    $(window).scroll(function(){
        var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
        var windowHeight = $(window).height(); // get the height of the window
        var docHeight = $(document).height();

        for (var i=0; i < aArray.length; i++) {
            var theID = aArray[i];
            var divPos = $(theID).offset().top-60; // get the offset of the div from the top of page
            var divHeight = $(theID).height(); // get the height of the div in question
            if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
                $("a[href='" + theID + "']").addClass("active");
            } else {
                $("a[href='" + theID + "']").removeClass("active");
            }
        }

        if(windowPos + windowHeight == docHeight) {
            if (!$("nav li:last-child a").hasClass("nav-active")) {
                var navActiveCurrent = $(".nav-active").attr("href");
                $("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
                $("nav li:last-child a").addClass("nav-active");
            }
        }
    });
});

最佳答案

您的 jQuery 在 anchor 上使用 active 类,但您在第一个元素的 li 上使用了 active 类,只需将它移动到 anchor 标记,如下所示:

<li><a class="scroll active" href="#test1">test1</a></li>

DEMO

关于jquery - 单页网站上的事件 div 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25242316/

相关文章:

html - 导航窗口问题

javascript - 如何防止固定按钮与页脚区域重叠并将按钮停止在页脚所在位置的顶部

html - 在 html/css 中显示图像的标准兼容和/或最佳实践方式

javascript - Jquery:点击时使用SetInterval

javascript - 轻松限制选中的复选框 jquery ui

java - Hibernate 查询更新

css help : only webkit rendering li bullets, 应该被隐藏

jquery - 为元素添加随机边距

javascript - 找到下一个 div-jquery 中存在的下一个元素的 id

php - 无限滚动多列?