我们做一个简易的选项卡,但是适用所有的选项卡(自改),首先我们来先把页面基本样式写好
- 周一
- 周三
- 周五
医务科
警卫科
教育科
下面是页面的基础css,user-select:none;可以禁止选中文字。
* { margin: 0; padding: 0; } .box1 { width: 300px; height: 300px; background-color: #bfa; } .box2 { width: 300px; height: 300px; background-color: orange; } .box3 { width: 300px; height: 300px; background-color: skyblue; } li { list-style: none; display: inline-block; width: 97px; height: 50px; text-align: center; line-height: 50px; background-color: pink; cursor: pointer; /* 无法选中文字 */ user-select: none; box-sizing: border-box; vertical-align: middle; } .active { border-top: 2px solid green; } /* div全部先默认隐藏 */ div { display: none; } /* 单独给一个显示的 */ .block { display: block; }
下面是js的部分,首先要获取所有的li和div,然后对它们进行操作
//获取所有的li和div let lis = document.querySelectorAll('li'); divs = document.querySelectorAll('div'); //添加三个点击事件 for (let i = 0; i < lis.length; i++) { lis[i].onclick = function() { document.querySelector('.active').classList.remove('active'); document.querySelector('.block').classList.remove(('block')); //记住上面两句和下面两句不能换位置,否则会出错 lis[i].classList.add('active'); divs[i].classList.add('block'); } }
for循环里,最后的俩句定义不能放在前,放在前面就会变成一次性的无法来回切换,而导致体验效果差。
做了个基础的模板,要想更好看一点,自己改改就行。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/199437.html原文链接:https://javaforall.net
