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

请看代码如下:

<!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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值