【问题标题】:Changing Navigation Bar Background Colour?更改导航栏背景颜色?
【发布时间】:2013-08-05 00:30:38
【问题描述】:

我目前正在尝试为我的一个网站设计一个导航栏。此导航栏将位于网页顶部。

问题是当我将鼠标悬停在项目上时,我可以让项目改变颜色,但一旦页面处于活动状态,就无法让项目保持悬停状态。例如,如果我想去“主页”,我会将鼠标悬停在导航栏中的“主页”项上,当我单击它返回“index.php”时,它会变成灰色"在导航栏中将保持灰色。 (导航栏背景为黑色)。

我已经格式化了一个单行表格和几条数据,它们将用作链接。这就是 HTML 代码的样子:

<div id="header_banner">
<table id="header_banner_table">
    <tr id="header_banner_row">
        <td id="header_banner_a"><a class ="link1" href="">Item 1</a></td>
        <td id="header_banner_b"><a class ="link1" href="">Item 2</a></td>
        <td id="header_banner_c"><a class ="link1" href="">Item 3</a></td>
        <td id="header_banner_d"><a class ="link1" href="">Item 4</a></td>
        <td id="header_banner_e"><a class ="link1" href="">Item 5</a></td>
        <td id="header_banner_f"><a class ="link1" href="">Item 6</a></td>
        <td id="header_banner_g"><a class ="link1" href="">Item 7</a></td>
    </tr>
</table>
</div>

这里是一些 CSS:

#header_banner {
    display: block;
    position: fixed;
    top: 0px;
    left: 0px;
    right: 0px;
    width: 100%;
    height: 71px;
    background-color: black;
    color: white;
    font-size: 18px;
    text-align:center;
    text-transform: uppercase;
    text-decoration: none;
}

#header_banner_table {
    position: fixed;
    top: 0px;
    width: 60%;
    padding: 0px;
    margin-left: 20%;
    margin-right: 20%;
}

.link1 {
position: relative;
display: block;
color: white;
text-decoration: none;
padding-top: 23px;
padding-bottom: 23px;
padding-left: 20px;
padding-right: 20px;
}

.link1:hover{
position: relative;
display: block;
text-decoration: none;
color: white;
padding-top: 23px;
padding-bottom: 23px;
padding-left: 20px;
padding-right: 20px;
background-color: gray;
}

所以目前导航栏的背景是黑色的,当你将鼠标悬停在某个东西上时,它会变成灰色。当该页面处于活动状态时,我希望它保持灰色。

有什么解决办法吗?

提前谢谢你。

【问题讨论】:

    标签: html css navigation hyperlink


    【解决方案1】:

    试试

    :focus 
    

    :active
    

    但我认为它需要被点击。

    【讨论】:

    • 感谢您的回复。但是活动状态仅适用于单击按钮时,而不是之后。因此,如果您按住按钮单击,它将激活。
    【解决方案2】:

    你熟悉 jQuery 吗?如果我和你有同样的想法,你应该可以用 jQuery 来做。

    var path = window.location.pathname;
    
    $('#header_banner_row a').each(function(){
        if( $(this).attr('href') === path ){
            $(this).addClass('active');
        }
    });
    

    所以基本上,var path 是浏览器导航栏中 .com 之后的任何内容。如果该路径与标题中的 a 之一相同,它将获得一个活动类,您可以将其设置为灰色。

    【讨论】:

    • 感谢您的回复。不幸的是,我不熟悉 jQuery。我不完全确定你的意思,或者如何实现它。请给我看看好吗?
    • 在你的网站头部包含&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt;,在包含jQuery之后你可以包含一个script.js来保存上面的代码。只要确保你有jQuery(document).ready(function($){ // your code here });。如果脚本没有包含在准备好的函数中,事情就会出错。此外,最好的做法是在结束正文标记之前包含自定义脚本。
    • 再次感谢。我提出了另一个解决方案,我发现它也可以帮助我处理许多其他情况。我正在使用 PHP 有条件地应用 CSS 样式表。我不确定这是否是一种可接受的方法,但它确实有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2017-04-30
    • 1970-01-01
    • 2018-01-05
    • 2020-08-12
    • 1970-01-01
    • 2015-05-27
    相关资源
    最近更新 更多