Bootstrap Nav-link - 根据滚动更改字体颜色

问题描述

这是我的第一篇文章,如果您能帮助我解决这个问题,我将不胜感激。 我已经阅读了几篇文章,但到目前为止还没有找到解决方案。

我正在使用 Bootstap (v5.0) 的导航栏组件。 我想在用户向下滚动时更改导航栏和导航链接颜色。

到目前为止,我已经成功地改变了导航栏的颜色,但没有改变导航链接的颜色。 我已将代码片段附加到帖子中。

预先感谢您的帮助:-)

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textSize="20dp"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:text="Im trying to use marquee effect on the listitems of a recyclerview but it does not work even though" />
var navBar = document.getElementById('navbar')
var textNavBars = document.querySelectorAll('a.nav-link');

window.onscroll = function () {
    if (document.body.scrollTop >= 200 || document.documentElement.scrollTop >= 200) {
        navBar.classList.add('nav-colored');
        navBar.classList.remove('nav-transparent');
        for (const textNavBar of textNavBars) {
            textNavBar.classList.add('text-transparent')
            textNavBar.classList.add('text-colored')
        }
    } else {
        navBar.classList.add('nav-tranparent');
        navBar.classList.remove('nav-colored');
        for (const textNavBar of textNavBars) {
            textNavBar.classList.add('text-colored')
            textNavBar.classList.add('text-transparent')
        }
    }
}
.navbar{
    text-transform: uppercase;
}

.nav-colored { 
    background-color:#FF7F2F; 
    transition: background-color 3s
}
.nav-transparent{ 
    background-color:transparent;
    transition: background-color 3s;
}

.text-transparent{
    color: black;
}
.text-colored{
    color: #FF7F2F;
}

解决方法

您的 .text-colored 样式被此 Bootstrap 的样式覆盖:

.navbar-light .navbar-nav .nav-link {
    color: rgba(0,.55);
}

由于上面的样式是使用三个类来选择链接,所以它的选择器更具体,所以它会被应用而不是只使用一个类:

.text-colored {
    color: #FF7F2F;
}

要了解有关 CSS 特异性及其计算方式的更多信息,请参阅 Specificity - CSS: Cascading Style Sheets | MDN

解决您的问题的方法是将 !important 规则添加到您的样式声明中:

.text-colored {
    color: #FF7F2F !important;
}