HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<header class="header"> header </header> <main class="main"> <div class="sidebar"> <div class="menu"> <ul> <li data-href="#m1">栏目一</li> <li data-href="#m2">栏目二</li> <li data-href="#m3">栏目三</li> <li data-href="#m4">栏目四</li> <li data-href="#m5">栏目五</li> </ul> </div> </div> <div class="content"> <div id="m1" class="item" style="background:#999;">一</div> <div id="m2" class="item" style="background:#888;">二</div> <div id="m3" class="item" style="background:#777;">三</div> <div id="m4" class="item" style="background:#666;">四</div> <div id="m5" class="item" style="background:#555;">五</div> </div> </main> <footer class="footer"> footer </footer> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
* { margin: 0; padding: 0; box-sizing: border-box; } ul, li { list-style: none; } body { font-size: 50px; color: #333; } .header { padding: 50px; text-align: center; background: #ccc; } .main { margin: 0 auto; width: 100%; padding: 20px; overflow: hidden; } .footer { padding: 100px 0; text-align: center; overflow: hidden; background: #000; } .sidebar { float: left; width: 25%; } .sidebar li { margin-bottom: 1px; padding: 20px; line-height: 50px; font-size: 18px; background: #f0f0f0; cursor: pointer; transition: all 0.5s; } .sidebar li.cur { color: #fff; background: #000; } .content { float: right; width: 70%; } .content .item { padding: 300px 0; text-align: center; overflow: hidden; } |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js // https://cdn.bootcdn.net/ajax/libs/sticky-sidebar/3.3.1/jquery.sticky-sidebar.js var a = new StickySidebar(".sidebar", { topSpacing: 20, bottomSpacing: 20, containerSelector: ".content", innerWrapperSelector: ".menu" }); // 点击导航栏滑动到对应板块 $(".menu li").eq(0).addClass("cur"); $(".menu li").on("click", function () { $(this).addClass("cur").siblings().removeClass("cur"); var index = $(this).attr("data-href"); var elOffset = $(index).offset().top; $("html,body").animate({ scrollTop: elOffset }, 800); }); // 创建页面滚动完成之后的回调事件 $.fn.scrollEnd = function (callback, timeout) { $(this).scroll(function () { var $this = $(this); if ($this.data("scrollTimeout")) { clearTimeout($this.data("scrollTimeout")); } $this.data("scrollTimeout", setTimeout(callback, timeout)); }); }; // with a 1000ms timeout $(window).scrollEnd(function () { var ST = $(this).scrollTop(); $(".item").each(function () { var elOffset = $(this).offset().top; if (ST >= elOffset) { var index = $(this).index(); $(".menu li").eq(index).addClass("cur").siblings().removeClass("cur"); } }); }, 0); |
示例预览
See the Pen sticky-sidebar by Beiyu (@Beiyu) on CodePen.