簡體   English   中英

滾動錨鏈接上的活動導航

[英]Active Navigation On Scroll anchor links

幾個小時以來,我一直試圖弄清楚這一點。 我目前有一個固定的導航用於我的錨網站。 我希望在滾動瀏覽每個部分時更改菜單鏈接背景顏色。 像這樣: https://codepen.io/dbilanoski/pen/LabpzG 當我滾動瀏覽每個部分時,我只看到 hover 背景顏色而不是活動 state 顏色。 如果您有任何提示或建議,請提出建議。

謝謝!

 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>

您發送的 codepen 的技巧是所有部分的高度相同。 但是,有一種更靈活的方法可以做到這一點。 使用此解決方案,您檢查每個部分是否顯示在屏幕上,如果是,則在導航列表中突出顯示其按鈕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM