原生js实现Tab点击切换

看了下,网上给出的Demo大多是鼠标在移入的时候做tab切换,而我最近的博客项目是希望实现知乎登录页面那样的可以点击切换的tab,所以,我自己实现了一下

切换的实现思路

  • HTML:
    布局方面,我选择了div标签作为容器,做横向排列
    <div class="test selected"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    
  • CSS:
    因为在做切换时,选中的div是要有区别于其他未被选中div的,所以,可以通过不同的选择器来切换视图不同的状态
    .test {
        display: inline-block;
        height: 100px;
        width: 100px;
        background-color: rebeccapurple;
    }
    
    .selected {
        background-color: burlywood;
    }
    
  • JS:
    1、为每一个div元素添加点击事件
    2、通过点击获取的每一个div的index和当前选中的div的index做对比,如果相等,则表示点击的是已选中的div ,期间不会发生任何变化,反之,之前已选中的div失去选中状态,当前选中div添加选中状态
   function init() {
   // 默认选中的index,起始值为0
       let currentIndex = 0
       let divs = document.getElementsByClassName('test')
       for (let i = 0; i < divs.length; i++) {
           const div = divs[i]
           div.index = i
           div.addEventListener('click', () => {
               if (div.classList.contains('selected')) {
                   currentIndex = div.index
               }
               // 当前正在点选的div是已经选中的div
               if (currentIndex === div.index) {

               } else {
                   let currentDiv = divs[currentIndex]
                   currentDiv.classList.remove('selected')
                   let clickDiv = divs[div.index]
                   clickDiv.classList.add('selected')
                   //更新当前选中div的index
                   currentIndex = div.index
               }
           })
       }
   }
   init()

展示不同内容的实现思路

做tab切换大多都是为了点击不同的item去展示不同的内容,我说一下我的思路

  • HTML:
    放入希望去展示的布局就好
     <div class="first-content">
         第一页
     </div>
     <div class="second-content">
         第二页
     </div>
     <div class="third-content">
         第三页
     </div>
     <div class="fourth-content">
         第四页
     </div>
    
  • CSS:
    这里我使用了display属性来做视图的切换,而非visibility,这是因为visibility属性只是单纯的做了隐藏和展示,原有的流布局不会改变。
  .first-content,
  .second-content,
  .third-content,
  .fourth-content {
      display: none;
  }

  .first-content {
      display: block;
  }
  • JS:
    这一部分js的工作很简单,只需要拿到所有需要切换的内容,然后根据上面切换获得的index去取值,并修改style就可以
 const contents = document.querySelectorAll('.first-content, .second-content, .third-content, .fourth-content')
    function changeContent(index) {
        for (let i = 0; i < contents.length; i++) {
            const content = contents[i];
            if (index === i) {
                content.style.display = 'block'
            } else {
                content.style.display = 'none'
            }
        }
    }

完整代码

<!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>
</head>

<body>
    <!-- tab -->
    <div class="test selected"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <!-- content -->

    <div class="first-content">
        第一页
    </div>
    <div class="second-content">
        第二页
    </div>
    <div class="third-content">
        第三页
    </div>
    <div class="fourth-content">
        第四页
    </div>

</body>

<style>
    .test {
        display: inline-block;
        height: 100px;
        width: 100px;
        background-color: rebeccapurple;
    }

    .selected {
        background-color: burlywood;
    }

    .first-content,
    .second-content,
    .third-content,
    .fourth-content {
        display: none;
    }

    .first-content {
        display: block;
    }
</style>

<script>

    const contents = document.querySelectorAll('.first-content, .second-content, .third-content, .fourth-content')

    function init() {
        let currentIndex = 0
        let divs = document.getElementsByClassName('test')
        for (let i = 0; i < divs.length; i++) {
            const div = divs[i]
            div.index = i
            div.addEventListener('click', () => {
                if (div.classList.contains('selected')) {
                    currentIndex = div.index
                }
                if (currentIndex === div.index) {

                } else {
                    let currentDiv = divs[currentIndex]
                    currentDiv.classList.remove('selected')
                    let clickDiv = divs[div.index]
                    clickDiv.classList.add('selected')
                    currentIndex = div.index
                    changeContent(currentIndex)
                }
            })
        }
    }
    init()

    function changeContent(index) {
        for (let i = 0; i < contents.length; i++) {
            const content = contents[i];
            if (index === i) {
                content.style.display = 'block'
            } else {
                content.style.display = 'none'
            }
        }
    }

</script>

</html>
好的,我可以为您提供一个简单的例子: HTML: ```html <div class="tab"> <button class="tablinks" onclick="openTab(event, 'tab1')">Tab 1</button> <button class="tablinks" onclick="openTab(event, 'tab2')">Tab 2</button> <button class="tablinks" onclick="openTab(event, 'tab3')">Tab 3</button> </div> <div id="tab1" class="tabcontent"> <h3>Tab 1 Content</h3> <p>Some text...</p> </div> <div id="tab2" class="tabcontent"> <h3>Tab 2 Content</h3> <p>Some text...</p> </div> <div id="tab3" class="tabcontent"> <h3>Tab 3 Content</h3> <p>Some text...</p> </div> ``` CSS: ```css /* 隐藏所有tab内容 */ .tabcontent { display: none; } /* 标签页按钮样式 */ .tab button { background-color: #eee; border: none; color: black; padding: 10px 20px; cursor: pointer; } /* 激活的标签页按钮样式 */ .tab button.active { background-color: #ccc; } /* 标签页内容样式 */ .tabcontent { padding: 20px; border: 1px solid #ccc; } /* 第一个标签页默认显示 */ #tab1 { display: block; } ``` JavaScript: ```javascript function openTab(event, tabName) { // 获取所有的 tab 内容 var tabcontent = document.getElementsByClassName("tabcontent"); // 隐藏所有的 tab 内容 for (var i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // 获取所有的 tab 按钮 var tablinks = document.getElementsByClassName("tablinks"); // 将所有的 tab 按钮样式设置为非激活状态 for (var i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // 显示当前选中的 tab 内容 document.getElementById(tabName).style.display = "block"; // 设置当前选中的 tab 按钮为激活状态 event.currentTarget.className += " active"; } ``` 当用户点击任意一个标签页按钮时,`openTab`函数会被调用,隐藏所有标签页内容,将当前标签页内容设置为显示状态,同时将当前标签页按钮样式设置为激活状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值