简体   繁体   中英

How can I make the active navbar link change background color? Bootstrap 4.

I realize this question has been asked several times, but none of the solutions have worked for me. Here is my HTML:

<div  class="navbar-light" style="position: sticky; top: 0px; background: #fff0d8; z-index:99;">  <!--z-index to stay on top of everything else-->
<div class="container">
<ul class="sc-nav nav navbar-nav nav-fill w-100 flex-md-row">
<li class="nav-item">
    <a class="nav-link" href="#">oihdma</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="#">saaaassas</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="#">fffffffffffff</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="#">dsdsd</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="#">fsfsfsfs</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="#">fffff</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="#">xxxxx</a>
</li>
</ul>

And my script:

$(document).ready(function() {
    var url = this.location.pathname;
    var filename = url.substring(url.lastIndexOf('/')+1);
    $('a[href="' + filename + '"]').parent().addClass('active');
});

I left this script in the page footer so it is executed after page load.

Finally, my CSS:

  ul.nav a:hover, ul.nav a:focus, ul.nav a:active { background-color: #FDCBA3;} 

Hover and focus work as intended, but NOT active. The script makes the link active, the color of the text changes and that works fine. But the background color won't change. It changes on hovering and on focus, but not when clicked.

the :active pseudo-class is different than the .active class you're setting in your Javascript.

Try the following:

ul.nav a:hover, ul.nav a:focus, ul.nav a.active { background-color: #FDCBA3;} 

I inspected the active element in Firefox and realized that I was changing the wrong CSS. This is what worked:

ul.nav a:hover, ul.nav a:focus, .active { background-color: #FDCBA3;} 

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