国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 web前端 js教程 為活動狀態(tài)和可擴展選單建立動態(tài)導航腳本

為活動狀態(tài)和可擴展選單建立動態(tài)導航腳本

Nov 08, 2024 am 01:14 AM

Creating a Dynamic Navigation Script for Active State and Expandable Menus

建立動態(tài) Web 應用程式時,使用者介面 (UI) 需要提供直覺的導航體驗。無論是具有多個產(chǎn)品類別的電子商務網(wǎng)站還是內(nèi)容豐富的管理儀表板,擁有活動狀態(tài)和可擴展菜單都可以增強可用性。在這篇文章中,我們將逐步建立一個 JavaScript 腳本,該腳本動態(tài)突出顯示導覽中的當前頁面,並根據(jù)使用者的路徑展開相關部分。

問題

當使用者瀏覽多層選單時,我們希望:

  1. 目前頁面連結上的活動狀態(tài)。
  2. 可擴充部分,如果使用者位於嵌套在選單中的頁面上,則會自動開啟。

讓我們看一個範例 HTML 結構以及如何新增 JavaScript 以使我們的選單變得聰明。

選單結構範例

這是一個典型的巢狀選單結構。我們將為選單中的每個項目使用 menu-item,為連結使用 menu-link,為可折疊子選單使用 menu-sub。

<!-- Categories -->
<li>



<p>In this structure:</p>

<ul>
<li>Each main menu link (menu-toggle) opens a submenu when clicked.</li>
<li>The actual pages are in the submenu links (menu-link).</li>
</ul>

<h3>
  
  
  The JavaScript Solution
</h3>

<p>We’ll use JavaScript to:</p>

<ol>
<li>Identify the current page.</li>
<li>Apply an active class to the link that matches the current URL.</li>
<li>Add an open class to the parent menu if the link is inside a collapsed submenu.</li>
</ol>

<p>Here’s the JavaScript code:<br>
</p>

<pre class="brush:php;toolbar:false"><script>
    window.onload = function () {
        const currentPath = window.location.pathname; // Get the current path
        const links = document.querySelectorAll('.menu-link'); // Select all menu links

        links.forEach(function (link) {
            // Check if the link's href matches the current page's path
            if (link.getAttribute('href') === currentPath) {
                // Add 'active' class to the parent 'li' element of the link
                const menuItem = link.closest('.menu-item');
                if (menuItem) {
                    menuItem.classList.add('active');

                    // Check if the link is within a 'menu-sub', expand the parent menu
                    const parentMenu = menuItem.closest('.menu-sub');
                    if (parentMenu) {
                        // Add 'open' class to the parent 'menu-item' of the submenu
                        const parentMenuItem = parentMenu.closest('.menu-item');
                        if (parentMenuItem) {
                            parentMenuItem.classList.add('open');
                        }
                    }
                }
            }
        });
    };
</script>

分解代碼

  1. 取得目前路徑
   const currentPath = window.location.pathname;

這會取得目前頁面的路徑(例如,/inventory-issues),我們將用它來與選單中每個連結的 href 進行比較。

  1. 選擇選單連結
   const links = document.querySelectorAll('.menu-link');

我們選擇具有選單連結類別的所有元素,假設這些元素包含指向網(wǎng)站各個部分的連結。

  1. 符合目前頁面
   if (link.getAttribute('href') === currentPath) {

對於每個鏈接,我們檢查其 href 是否與 currentPath 匹配。如果是,則該連結適用於目前頁面。

  1. 設定活動狀態(tài)
   menuItem.classList.add('active');

我們?yōu)樽罱倪x單項目新增一個活動類,允許我們設定活動頁面連結的樣式。

  1. 展開父選單
   const parentMenuItem = parentMenu.closest('.menu-item');
   parentMenuItem.classList.add('open');

如果活動連結位於子選單 (menu-sub) 內(nèi),這部分程式碼將尋找包含該子選單的父選單項目並新增開放類,將其展開。

為活動和開放狀態(tài)添加 CSS

您需要為 CSS 中的活動類別和開放類別定義樣式:

<!-- Categories -->
<li>



<p>In this structure:</p>

<ul>
<li>Each main menu link (menu-toggle) opens a submenu when clicked.</li>
<li>The actual pages are in the submenu links (menu-link).</li>
</ul>

<h3>
  
  
  The JavaScript Solution
</h3>

<p>We’ll use JavaScript to:</p>

<ol>
<li>Identify the current page.</li>
<li>Apply an active class to the link that matches the current URL.</li>
<li>Add an open class to the parent menu if the link is inside a collapsed submenu.</li>
</ol>

<p>Here’s the JavaScript code:<br>
</p>

<pre class="brush:php;toolbar:false"><script>
    window.onload = function () {
        const currentPath = window.location.pathname; // Get the current path
        const links = document.querySelectorAll('.menu-link'); // Select all menu links

        links.forEach(function (link) {
            // Check if the link's href matches the current page's path
            if (link.getAttribute('href') === currentPath) {
                // Add 'active' class to the parent 'li' element of the link
                const menuItem = link.closest('.menu-item');
                if (menuItem) {
                    menuItem.classList.add('active');

                    // Check if the link is within a 'menu-sub', expand the parent menu
                    const parentMenu = menuItem.closest('.menu-sub');
                    if (parentMenu) {
                        // Add 'open' class to the parent 'menu-item' of the submenu
                        const parentMenuItem = parentMenu.closest('.menu-item');
                        if (parentMenuItem) {
                            parentMenuItem.classList.add('open');
                        }
                    }
                }
            }
        });
    };
</script>

這種方法的好處

  • 自動活動狀態(tài):無需在每個頁面上對活動連結進行硬編碼。該腳本動態(tài)更新活動連結。
  • 可擴充選單:使用者只能看到與目前頁面相關的部分,減少手動開啟選單的需要。
  • 可重複使用:此腳本足夠通用,可以與各種巢狀選單結構一起使用,使其適應多種類型的網(wǎng)站。

?來自埃迪古萊

以上是為活動狀態(tài)和可擴展選單建立動態(tài)導航腳本的詳細內(nèi)容。更多資訊請關注PHP中文網(wǎng)其他相關文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發(fā)現(xiàn)涉嫌抄襲或侵權的內(nèi)容,請聯(lián)絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Java vs. JavaScript:清除混亂 Java vs. JavaScript:清除混亂 Jun 20, 2025 am 12:27 AM

Java和JavaScript是不同的編程語言,各自適用於不同的應用場景。 Java用於大型企業(yè)和移動應用開發(fā),而JavaScript主要用於網(wǎng)頁開發(fā)。

掌握JavaScript評論:綜合指南 掌握JavaScript評論:綜合指南 Jun 14, 2025 am 12:11 AM

評論arecrucialinjavascriptformaintainingclarityclarityandfosteringCollaboration.1)heelpindebugging,登機,andOnderStandingCodeeVolution.2)使用林格forquickexexplanations andmentmentsmmentsmmentsmments andmmentsfordeffordEffordEffordEffordEffordEffordEffordEffordEddeScriptions.3)bestcractices.3)bestcracticesincracticesinclud

JavaScript評論:簡短說明 JavaScript評論:簡短說明 Jun 19, 2025 am 12:40 AM

JavascriptconcommentsenceenceEncorenceEnterential gransimenting,reading and guidingCodeeXecution.1)單inecommentsareusedforquickexplanations.2)多l(xiāng)inecommentsexplaincomplexlogicorprovideDocumentation.3)

如何在JS中與日期和時間合作? 如何在JS中與日期和時間合作? Jul 01, 2025 am 01:27 AM

JavaScript中的日期和時間處理需注意以下幾點:1.創(chuàng)建Date對像有多種方式,推薦使用ISO格式字符串以保證兼容性;2.獲取和設置時間信息可用get和set方法,注意月份從0開始;3.手動格式化日期需拼接字符串,也可使用第三方庫;4.處理時區(qū)問題建議使用支持時區(qū)的庫,如Luxon。掌握這些要點能有效避免常見錯誤。

JavaScript與Java:開發(fā)人員的全面比較 JavaScript與Java:開發(fā)人員的全面比較 Jun 20, 2025 am 12:21 AM

JavaScriptIspreferredforredforwebdevelverment,而Javaisbetterforlarge-ScalebackendsystystemsandSandAndRoidApps.1)JavascriptexcelcelsincreatingInteractiveWebexperienceswebexperienceswithitswithitsdynamicnnamicnnamicnnamicnnamicnemicnemicnemicnemicnemicnemicnemicnemicnddommanipulation.2)

為什麼要將標籤放在的底部? 為什麼要將標籤放在的底部? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript:探索用於高效編碼的數(shù)據(jù)類型 JavaScript:探索用於高效編碼的數(shù)據(jù)類型 Jun 20, 2025 am 12:46 AM

javascripthassevenfundaMentalDatatypes:數(shù)字,弦,布爾值,未定義,null,object和symbol.1)numberSeadUble-eaduble-ecisionFormat,forwidevaluerangesbutbecautious.2)

Java和JavaScript有什麼區(qū)別? Java和JavaScript有什麼區(qū)別? Jun 17, 2025 am 09:17 AM

Java和JavaScript是不同的編程語言。 1.Java是靜態(tài)類型、編譯型語言,適用於企業(yè)應用和大型系統(tǒng)。 2.JavaScript是動態(tài)類型、解釋型語言,主要用於網(wǎng)頁交互和前端開發(fā)。

See all articles