50行实现最简单的js原生选项卡,前端面试必考!

该文章展示了如何使用JavaScript实现最简单的选项卡功能,通过遍历DOM元素,设置事件监听器来切换内容展示,同时配合CSS实现样式控制。当点击按钮时,对应的卡片内容会显示,其他隐藏。
摘要由CSDN通过智能技术生成

50行实现最简单的js原生选项卡,前端面试必考!

一、dom结构
<input type="button" value="1" class="active">
<input type="button" value="2">
<input type="button" value="3">
<div class="card" style="display: block;">1111</div>
<div class="card">2222</div>
<div class="card">3333</div>
二、script标签
window.onload = function () {
    var allinput = document.getElementsByTagName('input')
    var allcard = document.getElementsByClassName('card')
    for (let i = 0; i < allinput.length; i++) {
        //循环遍历每一个input的button i为index
        allinput[i].onclick = function () {
            //先将所有的选项初始化为class="" ,且样式为display:none
            for (let j = 0; j < allinput.length; j++) {
                allinput[j].className = "";
                allcard[j].style.display = "none";
            }
            //将选中的那个index为i的classname设置为active,style显示出来
            allinput[i].className = "active";
            allcard[i].style.display = "block";
        }
    }
}
三、css样式
.card {
    display: none;
    border: 1px solid red;
    width: 80px;
    height: 80px;
}
.active {
	color: red;
}

完成!撒花!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

四、效果

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值