How to dynamically change the color of the selected menu item of a web page?

后端 未结 8 1425
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 14:55

I am new to developing web pages. I am looking to create menus similar to the ones in stackoverflow.com (like Questions, Tags, Users shown above). How do I change the color

相关标签:
8条回答
  • 2020-12-13 15:33

    I'm late to this question, but it's really super easy. You just define multiple tab classes in your css file, and then load the required tab as your class in the php file while creating the LI tag.

    Here's an example of doing it entirely on the server:

    CSS

    html ul.tabs li.activeTab1, html ul.tabs li.activeTab1 a:hover, html ul.tabs li.activeTab1 a  { 
        background: #0076B5;
        color: white;
        border-bottom: 1px solid #0076B5;
    }
    
    html ul.tabs li.activeTab2, html ul.tabs li.activeTab2 a:hover, html ul.tabs li.activeTab2 a {
        background: #008C5D;
        color: white;
        border-bottom: 1px solid #008C5D;
    }
    

    PHP

    <ul class="tabs">
        <li <?php print 'class="activeTab1"' ?>>
            <a href="<?php print 'Tab1.php';?>">Tab 1</a>
        </li>
    
        <li <?php print 'class="activeTab2"' ?>>
            <a href="<?php print 'Tab2.php';?>">Tab 2</a>
        </li>
    </ul>
    
    0 讨论(0)
  • 2020-12-13 15:35

    It would probably be easiest to implement this using JavaScript ... Here's a JQuery script to demo ... As the others mentioned ... we have a class named 'active' to indicate the active tab - NOT the pseudo-class ':active.' We could have just as easily named it anything though ... selected, current, etc., etc.

    /* CSS */
    
    #nav { width:480px;margin:1em auto;}
    
    #nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }
    
    #nav ul li{display:inline;} 
    
    #nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;} 
    
    #nav ul li a:hover{background:#ff9900; color:#ffffff;} 
    
    #nav ul li a.active {background:#ff9900; color:#ffffff;} 
    
    /* JQuery Example */
    
    <script type="text/javascript">
    $(function (){
    
        $('#nav ul li a').each(function(){
            var path = window.location.href;
            var current = path.substring(path.lastIndexOf('/')+1);
            var url = $(this).attr('href');
    
            if(url == current){
                $(this).addClass('active');
            };
        });         
    });
    
    </script>
    
     /* HTML */
    
    <div id="nav" >
        <ul>
            <li><a href='index.php?1'>One</a></li>
            <li><a href='index.php?2'>Two</a></li>
            <li><a href='index.php?3'>Three</a></li>
            <li><a href='index.php?4'>Four</a></li>
        </ul>
    </div>
    
    0 讨论(0)
提交回复
热议问题