案例3-选项卡-另一种记录当前选择的


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

    <style>

        .active {

            background: red;

        }

        div {

            font: 200px "宋体";

            display: none;

        }

        .show {

            display: block;

        }

    </style>

</head>

<body>

<button class="btn active">按钮1</button> 

<button class="btn">按钮2</button> 

<button class="btn">按钮3</button> 

<button class="btn">按钮4</button> 

<div class="show">内容1</div>

<div>内容2</div>

<div>内容3</div>

<div>内容4</div>

<script>

var btns = document.querySelectorAll(".btn");

var inners = document.querySelectorAll("div");

var now = 0; // 记录选中的是哪一个

/*

    点中当前让之前选中的,取消选中,然后给当前选中

*/

for(var i = 0; i < btns.length; i++){

    // 如果需要知道当前操作的是这组中的第几个一定记得加索引

  btns[i].index = i;

  btns[i].onmouseover = function(){

      // 清除现在选中的

        btns[now].classList.remove("active");

        inners[now].classList.remove("show");

        // 给当前加上选中效果


        this.classList.add("active");

        //console.log(this.index);

        inners[this.index].classList.add("show");

        //同步当前选中的是第几个

        now = this.index;

  }; 

}

</script>

</body>

</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容