我有一個響應菜單三個級別深,我有一些香草JavaScript切換ul
類。它可以工作,但只適用於導航中出現的第一個子菜單。這是爲了一個WordPress主題,所以我無法真正控制切換之後發生的子菜單的位置或數量。切換多個子菜單項沒有jQuery
請不要jQuery。
這裏的標記:
<nav id="site-navigation" class="main-navigation">
<div id="primary-menu" class="menu">
<ul>
<li class="page_item page-item-703"><a href="/blog/">Blog</a></li>
<li class="page_item page-item-701"><a href="/front-page/">Front Page</a></li>
<li class="page_item page-item-2"><a href="/sample-page/">Sample Page</a></li>
<li class="page_item page-item-6 page_item_has_children"><a href="/about/">About The Tests</a><span class="sub-nav-toggle">›</span>
<ul class='children'>
<li class="page_item page-item-1133"><a href="/about/page-image-alignment/">Page Image Alignment</a></li>
<li class="page_item page-item-1134"><a href="/about/page-markup-and-formatting/">Page Markup And Formatting</a></li>
<li class="page_item page-item-501"><a href="/about/clearing-floats/">Clearing Floats</a></li>
<li class="page_item page-item-155"><a href="/about/page-with-comments/">Page with comments</a></li>
<li class="page_item page-item-156"><a href="/about/page-with-comments-disabled/">Page with comments disabled</a></li>
</ul>
</li>
<li class="page_item page-item-174 page_item_has_children"><a href="/level-1/">Level 1</a><span class="sub-nav-toggle">›</span>
<ul class='children'>
<li class="page_item page-item-173 page_item_has_children"><a href="/level-1/level-2/">Level 2</a><span class="sub-nav-toggle">›</span>
<ul class='children'>
<li class="page_item page-item-172"><a href="/level-1/level-2/level-3/">Level 3</a></li>
<li class="page_item page-item-746"><a href="/level-1/level-2/level-3a/">Level 3a</a></li>
<li class="page_item page-item-748"><a href="/level-1/level-2/level-3b/">Level 3b</a></li>
</ul>
</li>
<li class="page_item page-item-742"><a href="/level-1/level-2a/">Level 2a</a></li>
<li class="page_item page-item-744"><a href="/level-1/level-2b/">Level 2b</a></li>
</ul>
</li>
<li class="page_item page-item-146"><a href="/lorem-ipsum/">Lorem Ipsum</a></li>
<li class="page_item page-item-733"><a href="/page-a/">Page A</a></li>
<li class="page_item page-item-735"><a href="/page-b/">Page B</a></li>
</ul>
</div>
</nav><!-- #site-navigation -->
而這裏的腳本:
document.querySelector('.sub-nav-toggle').onclick = function(){
document.getElementsByClassName('children')[0].classList.toggle("active");
};
就像我說的,這只是切換出現在nav
第一子菜單。 .active
類會更改最大高度以顯示子菜單。
我使用這個腳本添加一個跨度一類.sub-nav-toggle
到li
:
/**
* Add toggles to menu items that have submenus.
*/
var x = document.body.querySelectorAll('.page_item_has_children > a');
var index = 0;
for (index = 0; index < x.length; index++) {
var navArrow = document.createElement('span');
navArrow.className = 'sub-nav-toggle';
navArrow.innerHTML = '›';
x[index].parentNode.insertBefore(navArrow, x[index].nextSibling);
}
我知道如何使用jQuery做到這一點,但我不希望加載所有的jQuery做這一項任務。
我看不到任何'在你的HTML代碼.SUB-NAV-toggle' –
抱歉,當頁面加載時,正在添加一個腳本。我只是將該代碼添加到帖子中。 –
我已經發布和更新了答案...請看看 –