Js鼠标经过选项卡实现原理Tab

2023-03-27 08:55:47

效果如下图:

实现原理:

选项卡顾名思义就是鼠标经过哪个模块就切换到相应的内容,其实就是个事件按钮添加一个className响应的内容通过display来实现。

1、首先获取事件元素:按钮和内容

2、通过for循环遍历所有的按钮添加鼠标事件(onmousemove);

3、清掉所有按钮中的高亮属性和内容的display样式

4、给当前经过的按钮添加一个高亮和对应内容的display显示为block

注意:给多个元素添加多个事件要用for循环遍历,

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>鼠标经过选项卡</title>
    <style>
     *{padding:0px;margin: 0px;}
      #tabBox{ width: 600px;height: 300px; border:1px solid #ddd; margin: 10px auto}
      ul{ height: 40px; line-height: 40px;width: 600px; background: #eee; }
      ul li{ float: left;list-style: none; width: 149px; text-align: center;cursor: pointer;border-right: 1px solid #fff;border-bottom: 1px solid #dedede; }
       ul li:last-child{border-right: 0px;}
       ul li.aseclect{ background: #fff;border-right:1px solid #ddd; border-bottom: 0px; }
      .tabContent div{padding:5px; display: none}
    </style>
    <script>
    window.onload=function(){
        var oTabBox=document.getElementById('tabTitle');
        var oLi=document.getElementsByTagName('li');
        var oTabContent=document.getElementById('tabContent');
        var oDiv=oTabContent.getElementsByTagName('div');
        for(var i=0;i<oLi.length;i++){
            oLi[i].myIndex=i;
            oLi[i].onmousemove=function(){
                for (var j = 0; j<oLi.length; j++) {
                    oLi[j].className='';
                    oDiv[j].style.display='none';
                    }
                oLi[this.myIndex].className='aseclect';
                //alert(this.myIndex);
                oDiv[this.myIndex].style.display='block';
            }
        }
        }
    </script>
</head>
<body>
    <div id='tabBox'>
            <ul>
                <li class="aseclect">第一个</li>
                <li class="">第二个</li>
                <li class="">第三个</li>
                <li class="">第四个</li>
            </ul>
        <div id='tabContent' class="tabContent">
          <div style="display: block;">
            我是第一个
          </div> 
          <div>
            我是第二个
          </div>
          <div>
            我是第三个
          </div> 
          <div>
            我是第四个
          </div>
        </div>

    </div>
</body>
</html>

 

  • 作者:dome-class
  • 原文链接:https://blog.csdn.net/yyYY19910220/article/details/85233703
    更新时间:2023-03-27 08:55:47