用split()根据选项卡在url后面添加锚值

来源:互联网 发布:股市交易软件 编辑:程序博客网 时间:2024/06/03 05:51

请看代码如下:

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>jQuery实现tab标签切换效果</title>    <script src="jquery/jquery 2.0.3/jquery-2.0.3.min.js"></script>    <style>    * {        margin: 0;        padding: 0;        list-style: none;    }        body {        font: 12px/1.5 Tahoma;    }        #outer {        width: 450px;        margin: 150px auto;    }        #tab {        overflow: hidden;        zoom: 1;        background: #afd;        border: 1px solid #afd;    }        #tab li {        float: left;        color: #000;        height: 30px;        cursor: pointer;        line-height: 30px;        padding: 0 20px;    }        #tab li.current {        color: #afd;        background: #d9f;    }        #content {        border: 1px solid #afd;        border-top-width: 0;    }        #content ul {        line-height: 25px;        display: none;        margin: 0 30px;        padding: 10px 0;    }    </style></head><body>    <div id="outer">        <ul id="tab">            <li id="tab1" class="current">tab1</li>            <li id="tab2">tab2</li>            <li id="tab3">tab3</li>        </ul>        <div id="content">            <ul style="display:block;">                <a href="">内容111</a>            </ul>            <ul>                <a href="">内容222</a>            </ul>            <ul>                <a href="">内容333</a>            </ul>        </div>    </div>    <script>    $(function() {        window.onload = function() {            var $a = $('#tab li');            var $b = $('#content ul');            $a.click(function() {                var $this = $(this); //$(this)表示把$a转换为jQuery对象,然后赋值给$this这个变量                  var $t = $this.index(); //相当于$this的兄弟元素赋值给 $t                  $a.removeClass();                $this.addClass('current');                $b.css('display', 'none');                $b.eq($t).css('display', 'block'); //遍历$t                  var locationHref = window.location.href;//取当前url                window.location.href = locationHref.split('#')[0] + '#' + this.id;//用#分割取第一个值,然后+#+id                           })        }        var _hash = window.location.hash;//取锚值,从#开始        console.log(_hash);    if(_hash == "#tab1"){        $("#tab1").click();    }else if(_hash == "#tab2"){        $("#tab2").click();    }else{    $("#tab3").click();    }    });    </script></body></html>

效果如图所示:
















0 0
原创粉丝点击