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

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

為活動狀態(tài)和可擴展菜單創(chuàng)建動態(tài)導航腳本

Nov 08, 2024 am 01:14 AM

Creating a Dynamic Navigation Script for Active State and Expandable Menus

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

問題

當用戶瀏覽多層菜單時,我們希望:

  1. 當前頁面鏈接上的活動狀態(tài)。
  2. 可擴展部分,如果用戶位于嵌套在菜單中的頁面上,則會自動打開。

讓我們看一個示例 HTML 結(jié)構(gòu)以及如何添加 JavaScript 以使我們的菜單變得智能。

菜單結(jié)構(gòu)示例

這是一個典型的嵌套菜單結(jié)構(gòu)。我們將為菜單中的每個項目使用 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');

我們向最近的菜單項添加一個活動類,允許我們設置活動頁面鏈接的樣式。

  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)更新活動鏈接。
  • 可擴展菜單:用戶只能看到與當前頁面相關的部分,減少手動打開菜單的需要。
  • 可重用:該腳本足夠通用,可以與各種嵌套菜單結(jié)構(gòu)一起使用,使其適應多種類型的網(wǎng)站。

?來自埃迪古萊

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

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應用程序,用于創(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 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。掌握這些要點能有效避免常見錯誤。

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

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

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

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

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

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

什么是在DOM中冒泡和捕獲的事件? 什么是在DOM中冒泡和捕獲的事件? Jul 02, 2025 am 01:19 AM

事件捕獲和冒泡是DOM中事件傳播的兩個階段,捕獲是從頂層向下到目標元素,冒泡是從目標元素向上傳播到頂層。1.事件捕獲通過addEventListener的useCapture參數(shù)設為true實現(xiàn);2.事件冒泡是默認行為,useCapture設為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委托,提高動態(tài)內(nèi)容處理效率;5.捕獲可用于提前攔截事件,如日志記錄或錯誤處理。了解這兩個階段有助于精確控制JavaScript響應用戶操作的時機和方式。

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