简体   繁体   中英

How add display: block when anchor tag class is active with jquery or javascript?

In my case I have menu like this:

<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>

How to add style display block if anchor tag is active?

First of all remove the "i" element closing tag from your "Accounts" link. After that You should not use inline styling when you are changing display value, instead use separate css file. I would move the display : none from inline to separate css file using selector.

 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; }

It is fairly simple to modify the display property of the parent element based upon some property of a child element using Javascript but in this case I'm not sure how the hyperlink will be assigned the active class when it resides within a hidden element ( 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>

For Menu Try this will helpfull

.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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM