经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTMLCSS » HTML5 » 查看文章
原生js、jQuery实现选项卡功能
来源:cnblogs  作者:一粒尘土  时间:2018/10/8 9:06:05  对本文有异议

在大家在网上平常浏览网页的时候,想必各位都会看到选项卡功能,在这里给大家详解一下用原生js、jQuery如何来写一些基本的选项卡

话不多说,先给各位看一下功能图:

                 

好了,下边开始写代码了:

HTML代码:

  1. <ul>
  2. <li class="click">red</li>
  3. <li>blue</li>
  4. <li>yellow</li>
  5. </ul>
  6. <div class="box">
  7. <div class="show"></div>
  8. <div></div>
  9. <div></div>
  10. </div>

CSS代码:

  1. *{
  2. margin: 0;
  3. padding: 0;
  4. }
  5. ul{
  6. overflow: hidden;
  7. /*注意父级元素塌陷,详情见博客*/
  8. }
  9. ul li{
  10. width: 100px;
  11. height: 30px;
  12. float: left;
  13. border: 1px solid #000;
  14. list-style: none;
  15. border-right: none;
  16. text-align: center;
  17. line-height: 30px;
  18. cursor: pointer;
  19. }
  20. ul li:last-child{
  21. border-right: 1px solid #000000;
  22. }
  23. .box{
  24. position: relative;
  25. }
  26. .box div{
  27. width: 304px;
  28. height: 300px;
  29. position: absolute;
  30. display: none;
  31. }
  32. .box div:first-child{
  33. background-color: red;
  34. }
  35. .box div:nth-child(2){
  36. background-color: blue;
  37. }
  38. .box div:last-child{
  39. background-color: yellow;
  40. }
  41. .box .show{
  42. display: block;
  43. }
  44. .box .hide{
  45. display: none;
  46. }
  47. .click{
  48. background-color: #ccc;
  49. }
基本样式的设置

 

原生JS写法:

 

  1. var liAll = document.querySelectorAll('li');//获取要操作的元素
  2. var divAll = document.querySelectorAll('.box div');//获取被操作的跟随元素
  3. for (var i = 0;i<liAll.length;i++) { //for循环为每一个元素添加点击事件
  4. liAll[i].index = i; //作用域的问题,如果for循环使用let声明,则不需要该行代码
  5. liAll[i].onclick = function () {
  6. for (var j = 0;j<liAll.length;j++) {
  7. liAll[j].className = "";//将所有被操作的元素的背景色消失
  8. divAll[j].className = "hide";//将所有被操作的元素全部隐藏
  9. }
  10. this.className = "click";//当前被点击的元素背景色改变
  11. divAll[this.index].className = "show";//将所有被操作的元素跟随显示
  12. }
  13. }

 

jQuery写法:

引入jQuery文件 网址:https://www.bootcdn.cn/jquery/

  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>

 

  1. $("li").each(function (index , ele) {//each循环遍历。得到所有的li index代表li的下表,ele元素
  2. $(this).click(function () {//$(this) 表示当前点击的元素
  3. $(this).addClass("click");
  4. $(this).siblings().removeClass("click");
  5. $(".box div:eq("+index+")").css({"display":"block"}); //eq 根据each循环得出index的所引值 取对应的div显示
  6. $(".box div:eq("+index+")").siblings().css({"display":"none"}); //对应的div隐藏
  7. });
  8. });

 

如果您有看不明白的地方,可以留言,咱们共同交流!

前端知识更新的很快,继续努力吧!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号