JS基础选项卡[通俗易懂]

(41) 2023-06-22 21:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说JS基础选项卡[通俗易懂],希望能够帮助你!!!。

        选项卡在网页中很常见,应用的也很广泛,还是考验我们对JavaScript的掌握和运用,接下来让我们看一下最基础的选项卡代码,代码里注释对每一步都有详细的讲解,跟着代码逻辑一点点进行下去就能掌握

<!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>tab选项卡</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            text-decoration: none;
            list-style: none;
        }
        ul li{
            width: 100px;
            height: 50px;
            background-color: #ccc;
            float: left;
            border: 1px solid black;
            text-align: center;
            line-height: 50px;
        }
        #box{
            position: absolute;
            top: 50px;
        }
        #box div{
            width: 406px;
            height: 200px;
            border: 1px solid black;
            display: none;
            text-align: center;
            line-height: 200px;
        }
    </style>
</head>
<body>
    <ul>
        <li>大橘</li>
        <li>英短</li>
        <li>美短</li>
        <li>布偶</li>
    </ul>
    <div id="box">
        <div class="bg" style="display: block;">1</div>
        <div class="bg">2</div>
        <div class="bg">3</div>
        <div class="bg">4</div>
    </div>

    <script>
        // 逻辑 :1、移动到哪个选项卡,哪个选项卡背景色就改变
        //        2、对应的内容区域就显示,同样,移出时,背景颜色恢复,对应的内容区域隐藏
        var lis = document.getElementsByTagName("li");
        var bgs = document.getElementsByClassName("bg");

        for(let i = 0 ; i < lis.length ; i++){

            // 进行元素数组下标的设置,这一步是必须的!
            lis[i].index = i;

            // 鼠标移入时对应的背景颜色就改变
                    //同时,选项卡通过下标对应的图片就随之显示
            lis[i].onmouseover = function(){
                // console.log(this.index);
                lis[i].style.backgroundColor = 'yellow';
                bgs[this.index].style.display = 'block';
            }
            
            // 鼠标移出时对应的背景颜色就恢复
                    同时,选项卡通过下标对应的图片就随之隐藏
            lis[i].onmouseout = function(){
                lis[i].style.backgroundColor='#ccc';
                bgs[this.index].style.display = 'none';
            }
        }
    </script>
</body>
</html>

上一篇

已是最后文章

下一篇

已是最新文章

发表回复