javascript - Jquery滚动,事件类的顶部偏移

标签 javascript jquery css scroll offset

你能帮我解决一件我无法处理的事情吗?

我在我的网站上使用了scrolling-nav.js作为顶部菜单 - 内部、外部等。http://lukaszradwan.com/www_architect/services.php

现在我使用此代码设置偏移量

$(window).scroll(function() {
if ($(".navbar").offset().top > 130) {
    $(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
    $(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});

$(function() {
$('a.page-scroll').bind('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top - 130
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
});
});

但是,例如,当您单击“外部”时,事件类在这个位置上并不完全工作。

我尝试使用另一个主题的方法,但我的“js”知识很差。 jquery scroll, change navigation active class as the page is scrolling, relative to sections

提前致谢。

最佳答案

目前,仅当节的顶部偏移量为 0 时才应用事件类。您可以使用 jquery 将其更改为其他值,例如 130。添加此代码:

$(window).scroll(function(){
    /* Get id of sections corresponding to top nav menu */
    var scroll_sections = []
    $('a.page-scroll').each(function(){
      scroll_sections.push($(this).attr('href'));
    })

    for (i in scroll_sections)
    {   
      /* Instead of 0, if the top position offset of section is 130 or less,
         we add active class for that section in nav menu */
      if ($(scroll_sections[i]).position().top <= $(window).scrollTop() + 130) 
      {
        $('nav li.active').removeClass('active');
        $('nav a').eq(i).parent().addClass('active');
      }
    }
});

关于javascript - Jquery滚动,事件类的顶部偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175034/

相关文章:

javascript - 启用双击删除单元格颜色

javascript - 如何通过.js将json数据加载到html

javascript - 剑道网格拖放问题

按钮高度不一致(跨浏览器)

javascript - 如何迭代嵌套 HTML 列表而不返回 "youngest"子级?

jquery - 带 CSS 的全高列?

javascript - 向元素添加另一个类,但作为第一类

html - 如何对齐子导航并使其正确

html - 如何在左上角的站点名称旁边添加 'anchor' 列表元素?

javascript - 使用 Jquery 的 Rails 应用程序 : Only allowed to select one checkbox (haml)