面向对象的选项卡切换

实现效果:
点击按钮,出现对应的div内容。常用于页面切换效果。

<!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>
    <style>
        .box button{
      
      
            width: 100px;
            height: 50px;
        }
        .box .active{
      
      
            background-color: pink;
        }
        .box div{
      
      
            width: 300px;
            height: 300px;
            border: 2px solid palegreen;
            display: none;
        }
        .box div.on{
      
      
            display: block;
        }
    </style>
</head>
<body>
    <div class="box">
        <button class="active">首页</button>
        <button>企业介绍</button>
        <button>新闻</button>
        <div class="on">腾讯网从2003年创立至今,已经成为集新闻信息,区域垂直生活服务、社会化媒体资讯和产品为一体的互联网媒体平台。腾讯网下设新闻、科技、财经、娱乐、体育、汽车、时尚等多个频道</div>
        <div>360一个主页,整个世界,为用户提供门户、新闻、视频、游戏、小说、彩票等各种分类的优秀内容和网站入口,提供简单便捷的上网导航服务。安全上网,从360导航开始。</div>
        <div>今天要下雨了,我要早点回去。</div>
    </div>
    <script>
        class Tab{
      
      
            constructor(parent){
      
      
                this.box = document.querySelector(parent);
                this.btns = this.box.querySelectorAll('button');
                this.divs = this.box.querySelectorAll('div');
                this.init();//调用入口方法
            }
            init(){
      
      
                for(let i = 0 ;i<this.btns.length; i++){
      
      
                    let that = this;  //注解1
                    this.btns[i].onclick = function(){
      
      
                    //注解2
                        for(let i = 0;i<that.btns.length;i++){
      
      
                        //注解3
                            that.btns[i].className = '';
                            that.divs[i].className = ''
                        }
                        // 只有点击的按钮和对应下标的div有样式
                        // that.btns[i].className = 'active' 这个和下面一行一个意思,只是写法不同
                        this.className = 'active';
                        that.divs[i].className = 'on'
                    }
                }
            }
        }

        // 实例化,传入参数
        new Tab('.box')
    </script>
</body>
</html>
  • 注解1:
    这里的方法中的this指向的是该方法的对象,也就是Tab(),即这里的this指向的是Tab()的所有属性和方法,目前使用this.btns还是正确的使用,能够找到Tab()中存在的bths属性值,也就是正常的btns集合。后面的点击事件的this不是指向Tab()的,所以要先在这里存一份正确的this,赋值给变量that,使用that以供后面的点击事件。
  • 注解2:
    进入点击事件之后,这里的this就变成了谁点击就是谁,即点击哪个button就是哪个button,这时的this就是’‘<button class="active">按钮</button>,点击事件里的 this.btns[i] 就相当于是’'<button class="active">按钮</button>.btns[i]btns集合btns[i],这肯定就会报错无法读取未定义的属性啦,所以要在注解1的位置先存一份正确this,赋值给that,以供这里使用
  • 注解3
    排他思想,也就是让所有的div和button清空样式,只让我们点击的按钮和对应下标的div有样式。
    另外因为let的i是块级作用域,所以这里两个 for循环的变量 i 重名也没有关系。

猜你喜欢

转载自blog.csdn.net/qq_43687594/article/details/125416062
今日推荐