练手小案例:用js实现选项卡效果

效果图:

话不多说,直接上代码!

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/public.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="box">
        <ul>
            <li data-i="0" data-name="item" class="active">1</li>
            <li data-i="1" data-name="item">2</li>
            <li data-i="2" data-name="item">3</li>
        </ul>
        <ol>
            <li class="active">1</li>
            <li>2</li>
            <li>3</li>
        </ol>
    </div>
    <script src="js/myjs.js"></script>
</body>
</html>

 CSS:

*{
    padding: 0;
    margin: 0;
}
ul,li,ol{
    list-style: none;
}
.box{
    width: 600px;
    height: 400px;
    /* border: 3px solid pink; */
    margin: 50px auto;
}
.box > ul{
    height: 60px;
    display: flex;
}
.box > ul >li{
    flex: 1;
    color: white;
    background-color: skyblue;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.box > ul >.active{
    background-color: orange;
}
.box > ol{
    width: 100%;
    height: 100%;
    position: relative;
}
.box > ol >li{
    width: 100%;
    height: 100%;
    position: absolute;
    background-color: purple;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 100px;
    color: white;
    opacity: 0;
}
.box > ol >.active{
    opacity: 1;
}

JavaScript:

let an = document.querySelectorAll("ul > li");
let nr = document.querySelectorAll("ol > li");
let box = document.querySelector(".box");
let index = 0;
function changeOne(i){
    an[index].className = "";
    nr[index].className = "";
    index = i;
    an[index].className = "active";
    nr[index].className = "active";
}
box.addEventListener("click",function(e){
    if(e.target.dataset.name === "item"){
        let i = e.target.dataset.i;
        changeOne(i);
    }
})

学会了记得点赞哦!

猜你喜欢

转载自blog.csdn.net/hu_666666/article/details/128422512