网站导航


Site navigation

我正在用HTML,CSS和PHP制作一个网站。我在页面顶部有一个导航,当您将鼠标悬停在按钮上时,它们会亮起。

现在,当您单击一个按钮并转到该特定页面时,我希望该页面的按钮亮起,表明您位于该页面上。我将如何做到这一点?在每个页面上定义一个变量然后在菜单中检查它是不可能的,因为我在网站上也有一个论坛,这需要我在每个页面上定义一个变量。

编辑

设法解决了我的问题。事实证明,我可以定义页面,对于论坛,我可以在论坛使用的设置文件中执行相同的操作。

在我的导航中,我只检查当前页面是什么:

<li id="news"><a <? if(PAGE == "INDEX") print 'class="active"'; ?> href="/">News</a></li>

类(或 ID)添加到 body 标记,如下所示:

<body class="Page1">...</body>

然后,在你的CSS中,你可以这样说:

.Page1 menu li, menu li:hover {...}

我不确定如何在 PHP 中检查当前页面 - 不过,这将是理想的。

不过,如果你想依赖JavaScript,我过去已经成功地使用了这个函数:

function highlightPage(id){
    //make sure DOM methods are understood
    if(!document.getElementsByTagName) return false;
    if(!document.getElementById) return false;
    if(!document.getElementById(id)) return false;
    var nav = document.getElementById(id);
    var links = nav.getElementsByTagName('a');
    for (var i=0; i < links.length; i++){
        var linkurl = links[i].getAttribute('href');
        var currenturl = window.location.href;
        //indexOf will return -1 on non-matches, so we're checking for a positive match
        if (currenturl.indexOf(linkurl) != -1) {
            links[i].className = "here";
            var linktext = links[i].lastChild.nodeValue.toLowerCase();
            document.body.setAttribute("id",linktext);
        }
    }
}

并在页面加载时加载函数:

function addLoadEvent(func){
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function(){
            oldonload();
            func();
        }
    }
}
addLoadEvent(function(){
    highlightPage('navigation');
    });

这假定您的导航具有"导航"的 ID,但您可以将其更改为所需的任何内容。该函数只是将"here"类附加到当前导航项。

这个脚本来自Jeremy Keith的"DOM脚本"。