javascript - 添加事件类以在单击和手动滚动时平滑页面滚动

标签 javascript jquery hyperlink

我有一个平滑的页面滚动脚本,但需要它向与当前查看的页面部分相对应的链接添加“事件”类。我知道有很多类似的帖子,但它们都只有在单击链接本身时才有效。我希望不仅在单击时应用/删除事件类,而且当您使用鼠标滚轮向下滚动页面时,它也应该使用该方法在链接之间相应地切换。

http://jsfiddle.net/pixeloco/sewcs4cr/

$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - $('nav').height()
    }, 1000);
    return false;
  }
}

(这个链接产生了我想要的结果,但是当我根据我的需要调整它时,事件类开始跳跃......加上有些东西似乎已经定义但从未使用过,这让我的非 js 聪明的大脑感到困惑比平时更多: http://jsfiddle.net/cse_tushar/Dxtyu/141/ )

最佳答案

好吧找到了一个解决方案,所以如果其他人正在寻找类似的东西,我希望这会有所帮助:http://jsfiddle.net/pixeloco/L57z4ntb/

function checkSectionSelected(scrolledTo){
        var threshold = 30;
        var i;
        for (i = 0; i < sections.length; i++) {
            var section = $(sections[i]);
            var target = getTargetTop(section);
            if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
                sections.removeClass("active");
                section.addClass("active");
            }
        };
    }
    checkSectionSelected($(window).scrollTop());
    $(window).scroll(function(e){
        checkSectionSelected($(window).scrollTop())
    });

关于javascript - 添加事件类以在单击和手动滚动时平滑页面滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25185447/

相关文章:

javascript - 如何在 Promise 完成后调用 axios 中的数组元素

javascript - 如何通过图像查找元素

html - 链接垂直对齐,高度 100%

javascript - 有没有一种方法可以将 JavaScript 对象转换为格式更清晰的另一个对象?

javascript - jQuery.eCalendar() - 对事件使用 for 循环

javascript - 制作幻灯片旋转

javascript - jQuery 查找整数并附加小数

django - 是否可以在 Django 中提供外部 URL 名称

python - 如何修改lxml自动链接更加自由?

javascript - 如何使用JS访问多个对象中的特定属性