js点击后添加active类名教程

常用脚本 20-11-11 101 0

常用的js点击后添加active类名或者js点击后添加on类名,下面教大家如何通过jquery导航栏点击及页面跳转后对应栏目添加选中效果。

html代码:

<header>

    <div class="navbar-nav">

        <li class="active"><a href="index.html">首页</a></li>

        <li><a href="news.html">新闻</a></li>

        <li><a href="activity.html">活动</a></li>

        <li><a href="project.html">项目</a></li>

    </div>

</header>

style样式代码:

<style>

        header{

            background-color: #C50B10;

            color: #FFF;

        }

        li{

            line-height: 50px;

            background-color: #C50B10;

            display: inline-block;

            padding: 0 20px;

        }

        li.active{

            background: rgba(0,0,0,.2);

        }

</style>

js代码:

<script>

    $(document).ready(function (){

        $(".navbar-nav>li").each(function(index){

            $(this).click(function(){

                $("li").removeClass("active");

                $("li").eq(index).addClass("active");

            });

        });

    });

</script>

但是一般页面的导航栏都是需要跳转页面的,上面的方法只在当前页面有效,跳转后就失效了。

要实现跳转后,对应的栏目自动添加选中效果,可以用下面的方法。

js代码:

<script>

    $(document).ready(function () {

        $(".navbar-nav>li a").each(function () {

            if ($($(this))[0].href == String(window.location))

                $(this).parent().addClass('active');

        });

    });

</script>


本文来自:以上内容来自互联网,如有侵权请联系客服

链接网址:http://cd.seowhy.com

分享:

SEO培训,扫码微信了解

评论

免费拨打  187-0592-1889 免费拨打  187-0592-1889
免费拨打:187-0592-1889拨打电话:187-0592-1889
微信二维码 微信二维码
手机二维码 手机二维码
返回顶部 返回顶部
返回顶部返回顶部
cache
Processed in 0.007403 Second.