如何改变当前页面的颜色HTML/CSS只?

wgxvkvu9  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(140)

我有一个导航菜单,需要改变我现在所在页面的颜色。有没有可能不添加后端逻辑?HTML

<div class="navigation">
            <ul>
                <li><a href="/short-reference">Short reference</a></li>
                <li><a href="/early-life">Early life</a></li>
                <li><a href="/main-page">Main page</a></li>
            </ul>
     </div>

CSS

.navigation{
    display: block;
    width: auto;
    height: 40px;
    background-color: #22438C;
    font-family: monospace;

}

.navigation ul{
    margin-left: 500px;
    list-style: none;
    
}

.navigation ul li{
    display: inline-block;
    position: relative;
    background-color: rgb(23, 23, 70);
    
}
.navigation ul li a{
    text-decoration: none;
    display: block;
    padding: 10px 12px;
    color: white;
    text-align: center;
}

因此,如果我在“短参考”页面,在导航菜单部分,这个页面将有黑色背景。

cgfeq70w

cgfeq70w1#

我不清楚你是想改变整个菜单的颜色还是只是改变特定的链接,但是如果你想改变链接,这就是你可以做的。
为一个名为.active的类创建CSS,然后使用JavaScript将该类应用于相应的菜单项。

<script type="text/javascript">
  // Sets the "active" class to the navigation link based on the current URL
  function setActiveNavLink() {
    const currentUrl = window.location.pathname;
    const navLinks   = document.querySelectorAll('.navigation a');

    for (let link of navLinks) {
      const isActive = link.getAttribute('href') === currentUrl;
      const listItem = link.parentElement;

      // Add 'active' class to the parent <li>
      if (isActive) listItem.classList.add('active'); 
    }
  }

  // Call the function to set the active navigation link when the page loads
  document.addEventListener('DOMContentLoaded', setActiveNavLink);
</script>
zed5wv10

zed5wv102#

我从两个方面解读了你的文章:(我假设你使用的是.html文件,你的导航栏在每个文件中实现)
如何改变当前页面的颜色HTML/CSS只?
给每一页给予一个ID。(我之所以对ID而不是类说,是因为每个页面的样式都是唯一的)
Ex.

#short-reference{
    background-color: #000000;
}

#searly-life{
    background-color: brown;
}

#main-page{
    background-color: rgba(225, 225, 225, 1);
}

因此,如果我在“短参考”页面,在导航菜单部分,这个页面将有黑色背景。
您可以为每个.html文件中的导航栏给予自己的ID。(**再次:**我之所以对ID而不是类说,是因为样式对于每个页面的导航栏都是唯一的)
Ex.

#short-reference-navbar{
    background-color: #000000;
}

#searly-life-navbar{
    background-color: brown;
}

#main-page-navbar{
    background-color: rgba(225, 225, 225, 1);
}

相关问题