![](/img/trans.png)
[英]How to add and remove active class to anchor tag within li using Jquery/Javascript
[英]How add display: block when anchor tag class is active with jquery or javascript?
就我而言,我有這樣的菜單:
<li class="">
<a href="#" class="">Accounts</i></a>
<ul style="display: none;">
<li class=""><a href="https://example.test/profile/index" class="active ">Profile</a></li>
<li class=""><a href="https://example.test/profile/edit" class="">Edit </a></li>
</ul>
</li>
如果錨標記處於活動狀態,如何添加樣式顯示塊?
首先,從“帳戶”鏈接中刪除“i”元素結束標記。 之后,在更改顯示值時不應使用內聯樣式,而應使用單獨的 css 文件。 我會使用選擇器將 display : none 從內聯移動到單獨的 css 文件。
ul { display: none; } // use this if you want to hover a:hover + ul { display: block; } // use this if you want to click a:focus + ul { display: block; }
這是相當簡單的修改基於使用JavaScript的子元素的某些屬性,但在這種情況下,我不知道怎么的超級鏈接將被分配的父元素的顯示屬性active
(當它位於一個隱藏的元素中類ul
)...
const getparent=(n,e)=>{//utility to find ancestor node of particular type while( n!=document.querySelector(e) )n=n.parentNode; return n; } // find all nodes that match the `active` class criteria and navigate up the DOM // until the UL element is found - change it's display property document.querySelectorAll('li a.active').forEach( a => getparent(a,'ul').style.display='block' )
<li class=""> <a href="#" class=""><i>Accounts</i></a> <ul style="display: none;"> <li class=""><a href="https://example.test/profile/index" class="active ">Profile</a></li> <li class=""><a href="https://example.test/profile/edit" class="">Edit </a></li> </ul> </li>
對於菜單嘗試這會有所幫助
.menu ul{
position: absolute;
display: none;
}
.menu >li{
display: inline-block;
vertical-align: top;
position: relative;
}
.menu li a{
display: block;
padding: 0px 10px;
}
.menu li:hover ul{
display: block;
}
<ul class="menu">
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a>
<ul>
<li><a href="#">Drop Down1</a></li>
<li><a href="#">Drop Down2</a></li>
<li><a href="#">Drop Down3</a></li>
</ul>
</li>
<li><a href="#">Menu 3</a>
<ul>
<li><a href="#">Drop Down1</a></li>
<li><a href="#">Drop Down2</a></li>
<li><a href="#">Drop Down3</a></li>
</ul>
</li>
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.