返回 jQuery 实例与特效代码列表
滚动与布局MIT兼容 jQuery 1.12 / 3.8 / 4.1

吸顶导航栏

滚动超过 Banner 区域后导航条自动切换紧凑吸顶态并点亮当前阅读章节。

兼容性说明:全版本兼容(含 slim 精简版)。

在线交互演示(独立沙箱)

$(function () {
  var $box = $('#sn-box'), $nav = $('#sn-nav');
  $box.on('scroll', function () {
    var st = $box.scrollTop();
    $nav.toggleClass('stuck', st > 55);
    $box.find('.sn-sec').each(function () {
      var relTop = $(this).position().top;
      if (relTop <= 60) {
        $nav.find('a').removeClass('active').filter('[data-sec="' + this.id + '"]').addClass('active');
      }
    });
  });
  $nav.on('click', 'a', function () {
    var id = $(this).data('sec');
    var targetTop = $box.scrollTop() + $('#' + id).position().top - 42;
    $box.scrollTop(targetTop);
  });
});
不用 jQuery 怎么写?(现代原生 JS / CSS 替代思路)

吸顶直接用 CSS position: sticky; top: 0,章节高亮用 IntersectionObserver 监听各 section。

.nav { position: sticky; top: 0; z-index: 10; }