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

wgxvkvu9  于 2023-10-14  发布在  其他
关注(0)|答案(2)|浏览(175)

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

  1. <div class="navigation">
  2. <ul>
  3. <li><a href="/short-reference">Short reference</a></li>
  4. <li><a href="/early-life">Early life</a></li>
  5. <li><a href="/main-page">Main page</a></li>
  6. </ul>
  7. </div>

CSS

  1. .navigation{
  2. display: block;
  3. width: auto;
  4. height: 40px;
  5. background-color: #22438C;
  6. font-family: monospace;
  7. }
  8. .navigation ul{
  9. margin-left: 500px;
  10. list-style: none;
  11. }
  12. .navigation ul li{
  13. display: inline-block;
  14. position: relative;
  15. background-color: rgb(23, 23, 70);
  16. }
  17. .navigation ul li a{
  18. text-decoration: none;
  19. display: block;
  20. padding: 10px 12px;
  21. color: white;
  22. text-align: center;
  23. }

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

cgfeq70w

cgfeq70w1#

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

  1. <script type="text/javascript">
  2. // Sets the "active" class to the navigation link based on the current URL
  3. function setActiveNavLink() {
  4. const currentUrl = window.location.pathname;
  5. const navLinks = document.querySelectorAll('.navigation a');
  6. for (let link of navLinks) {
  7. const isActive = link.getAttribute('href') === currentUrl;
  8. const listItem = link.parentElement;
  9. // Add 'active' class to the parent <li>
  10. if (isActive) listItem.classList.add('active');
  11. }
  12. }
  13. // Call the function to set the active navigation link when the page loads
  14. document.addEventListener('DOMContentLoaded', setActiveNavLink);
  15. </script>
展开查看全部
zed5wv10

zed5wv102#

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

  1. #short-reference{
  2. background-color: #000000;
  3. }
  4. #searly-life{
  5. background-color: brown;
  6. }
  7. #main-page{
  8. background-color: rgba(225, 225, 225, 1);
  9. }

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

  1. #short-reference-navbar{
  2. background-color: #000000;
  3. }
  4. #searly-life-navbar{
  5. background-color: brown;
  6. }
  7. #main-page-navbar{
  8. background-color: rgba(225, 225, 225, 1);
  9. }
展开查看全部

相关问题