静态页面中导航切换时的当前状态(四中方法)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>导航当前状态</title>
    <script src="jquery-1.8.2.min.js"></script>
</head>
<body onload="s35()">
<div ></div>

<script>
    //第一种方法:给当前页面导航添加class
    //优点:适用于每个页面
    //缺点:每个也页面都要声明ID(secondId),页面很多时,代码量大
    function s35() { document.getElementById('dhnews').className = "xz"; }

    //第二种方法:给当前页面设置ID,通过ID获取对应的索引值。为当前页面导航添加class
    //优点:适用于每个页面
    //缺点:每个也页面都要声明ID(secondId),页面很多时,代码量大
    var secondId = '16481';
    $("#cbg-main-nav").find("li").eq(topBottom(secondId)).addClass("current");
    function topBottom(secondId){
        switch(secondId){
            case '2613':
                return 0;
            case '2617':
                return 1;
            case '2622':
                return 4;
            case '16195':
                return 2;
            case '5712':
                return 4;
            case '2637':
                return 6;
            case '16481':
                return 3;
        }
    }

    //第三种方法:判断当前导航链接与页面链接
    //优点:可作为公共部分提出代码
    //缺点:只适用于在菜单栏有入口的页面
    $(document).ready(function(){
        $(".nav a").each(function(){
            $this = $(this);
            if($this[0].href==String(window.location)){
                $this.addClass("hover");
            }
        });
    });

    //第四种方法:判断页面链接与当前导航链接
    //优点:可作为公共部分提出代码
    //缺点:只适用于在菜单栏有入口的页面
    $(function () {
        var $SIDEBAR_MENU=$('#sidebar-menu');
        var CURRENT_URL = window.location.href.split('#')[0].split('?')[0];
        var pathName_URL = window.location.pathname.split('#')[0].split('?')[0];   //
        $SIDEBAR_MENU.find("a").filter(function(){return this.href==CURRENT_URL}).addClass("current-page");
        //处理个别不在菜单中的页面
        if(pathName_URL=="/gov/info/findInfoList" || pathName_URL=="/gov/info/findInfoById" || pathName_URL=="/gov/standard/findList"){
            $('#menu-article').find("a").addClass("current-page");
        }else if(pathName_URL=="/gov/transportCar/toByNo"){
            $('#js_to_list').find("a").addClass("current-page");
        }
    });

</script>

<!--<div class="nav">
    <ul>
        <li><a href="1.html"> 首页</a></li>
        <li><a href="2.html"> 个人资料</a></li>
        <li><a href="3.html"> 我的好友</a></li>
        <li><a href="4.html"> 消息管理</a></li>
    </ul>
</div>-->


</body>
</html>
原文地址:https://www.cnblogs.com/hjbky/p/8649796.html