原生javascript实现选项卡切换效果

原生javascript实现选项卡切换效果_第1张图片


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <style>
        .tab .title span{display: inline-block;padding:5px 10px;background:#ccc;}
        .title .active{color:red;}
        .hidden{display:none;}
        .content{width:200px;height:200px;border:1px solid #ccc;}
        .content .active{display: block;}
    style>
head>
<body>
    <div class="tab">
        <div class="title">
            <span class="active">1span>
            <span>2span>
            <span>3span>
        div>
        <div class="content">
            <div class="hidden active">1内容div>
            <div class="hidden">2内容div>
            <div class="hidden">3内容div>
        div>
    div>
body>
html>
<script>
    function $$(selector){
        return document.querySelectorAll(selector);
    }

    function $(selector){
        return document.querySelector(selector);
    }

    var tabbtn = $$(".tab .title span");
    var tabbox = $$(".tab .content div");

    for(var i = 0, len = tabbtn.length; i < len; i++){
        (function(k){
            tabbtn.item(k).onclick = function(){
                $(".title .active").classList.remove("active");
                this.classList.add("active");
                $(".content .active").classList.remove("active");
                tabbox.item(k).classList.add("active");
            }
        })(i);
    }

script>

你可能感兴趣的:(web前端,javascript)