开发者

Highlight active link

开发者 https://www.devze.com 2023-01-11 02:13 出处:网络
How can I have the active link highlighted when clicked but keep the home page link highlighted until another link is clicked?

How can I have the active link highlighted when clicked but keep the home page link highlighted until another link is clicked?

I'm using PHP if that helps.

Here is my (x)HTML code.

<div id="nav">
    <ul>
        <li><a href="http://localhost/link-1/" class="active">Link 1</a></li>
        <li><a href="http://localhost/link-2/">Link 2</a></li>
        <li><a href="http://localhost/link-3/">Link 3</a></li>
        <li><a hr开发者_StackOverflow社区ef="http://localhost/link-4/">Link 4</a></li>
    </ul>
</div>


I'm not in the spot to be able to test this right now, let me know if it work for you though.

var menuArray = new Array();

$(function() {


    $('div#nav ul li').each(function(i) {
        menuArray[i] = this;
        $(this).click(function() {
            for (var x in menuArray)
                if (x == this)
                    $(x).attr('class','active');
                else
                    $(x).attr('class','inactive');
        });
    });
});

EDIT alright, I was able to test this and it's working for me. Keep in mind that this needs to be after your HTML declaration.

$("li a").each(function(i) {
        $(this).click(function() {
             $(this).attr('class','selected');
             $("li a").not(this).attr('class','notselected');
        });
});


You can do a method in php, here is an example:

<div id="nav">
    <ul>
        <li><a href="http://localhost/link-1/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-1')?>>Link 1</a></li>
        <li><a href="http://localhost/link-2/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-2')?>>Link 2</a></li>
        <li><a href="http://localhost/link-3/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-3')?>>Link 3</a></li>
        <li><a href="http://localhost/link-4/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-4')?>>Link 4</a></li>
    </ul>
</div>
<?php
function activateLink($uri,$var) 
{
    if($uri==$var) {
        return 'class="active"';
    }
}
?>

On every page print $_SERVER['REQUEST_URI'] and pass the second parameter to the method.


That will not require PHP at all, however you can build it on PHP. I will demonstrate to you how to build this in HTML/CSS.

Try this CSS/HTML in your document (before your code):

<style>
       .active {
             color:#336699;
       }

       div#nav ul li a {
             color:#121212;
       }

       div#nav ul li a:visited {
             color:#336699;
       }
</style>

That should colour all the links blue if they have been visited, and if they havent it will be dark grey. However, if you want it to only highlight one link it's best to look at using JQuery as it has a multitude of functions to only choose the one that is being selected.

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号