简体   繁体   English

如何使活动的导航栏链接更改背景颜色? 引导程序4。

[英]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: 这是我的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: 最后,我的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. :active伪类与您在Javascript中设置的.active类不同。

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. 我检查了Firefox中的active元素,发现自己正在更改错误的CSS。 This is what worked: 这是有效的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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