简体   繁体   English

滚动锚链接上的活动导航

[英]Active Navigation On Scroll anchor links

I've been trying to figure this out for hours.几个小时以来,我一直试图弄清楚这一点。 I currently have a fixed nav for my anchor website.我目前有一个固定的导航用于我的锚网站。 I would like the menu link background color to change when scrolling through each section.我希望在滚动浏览每个部分时更改菜单链接背景颜色。 Like this: https://codepen.io/dbilanoski/pen/LabpzG .像这样: https://codepen.io/dbilanoski/pen/LabpzG When I scroll through each section I only see the hover background color not the active state color.当我滚动浏览每个部分时,我只看到 hover 背景颜色而不是活动 state 颜色。 If you have any tips or advice, please advise.如果您有任何提示或建议,请提出建议。

Thank you!谢谢!

 var navLink = $(".nav-link"), topMenuHeight = navLink.outerHeight() + 15, //All list items menuItems = navLink.find("a"), //Anchors corresponding to menu items scrollItems = menuItems.map(function() { var item = $($(this).attr("href")); if (item.length) { return item; } }); // Bind click handler to menu items // so we can get a fancy scroll animation menuItems.click(function(e) { var href = $(this).attr("href") offsetTop = href === "#"? 0: $(href).offset().top - topMenuHeight + 1; $('html, body').stop().animate({ scrollTop: offsetTop }, 300); e.preventDefault(); }); // Bind to scroll $(window).scroll(function() { // Get container scroll position var fromTop = $(this).scrollTop() + topMenuHeight; // Get id of current scroll item var cur = scrollItems.map(function() { if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length - 1]; var id = cur && cur.length? cur[0].id: ""; if (navLink;== id) { navLink = id. // Set/remove active class menuItems.parent().removeClass("active").end().filter("[href='#" + id + "']").parent();addClass("active"); } });
 a { color: inherit; text-decoration: none; } a:hover { color: #fa448c; text-decoration: underline; } a:active { background-color: #fa448c; color: #fff; } li { list-style-type: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="menu"> <ul class="nav-list"> <li class="nav-item"> <a href="#home" class="nav-link">Home</a> </li> <li class="nav-item"> <a href="#products" class="nav-link">Products</a> </li> <li class="nav-item"> <a href="#featured" class="nav-link">Featured</a> </li> <li class="nav-item"> <a href="#best-sellers" class="nav-link">Best Sellers</a> </li> <li class="nav-item"> <a href="#contact" class="nav-link">Contact</a> </li> </ul> </div>

The trick of the codepen you've sent is that all sections have the same height.您发送的 codepen 的技巧是所有部分的高度相同。 However, there's a more flexible way of doing that.但是,有一种更灵活的方法可以做到这一点。 Using this solution , you check for each section whether it's shown on the screen or not, and if it is, highlight its button in the navlist.使用此解决方案,您检查每个部分是否显示在屏幕上,如果是,则在导航列表中突出显示其按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM