栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JS实现选项卡实例详解

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JS实现选项卡实例详解

本文实例讲述了JS实现选项卡的方法。分享给大家供大家参考,具体如下:

思路:选项卡就是点击按钮切换到相应内容,其实就是点击按钮把内容通过display(block none)来实现切换的。

1、首先获取元素。

2、for循环历遍按钮元素添加onclick 或者 onmousemove事件。

3、因为点击当前按钮时会以高亮状态显示,所以要再通过for循环历遍把所有的按钮样式设置为空和把所有DIV的display设置为none。

4、把当前按钮添加样式,把当前DIV显示出来,display设置为block。

注:给多个元素添加多个事件要用for循环历遍。如选项卡是点击切换,当前按钮高度,点击和按钮高亮就是2个事件,所以要用2个for循环历遍。

HTML代码:


 
 
 
 
 1
 2
 3
 4


JS代码:



补充:用js写简单选项卡完整步骤

如图,最简单的纯粹的选项卡

第一步,当然是先写html代码和css样式





无标题文档

body,ul,li{margin:0; padding:0; font:12px/1.5 arial;}
ul,li{list-style:none;}
.wrap{width:500px; margin:20px auto;}
.hide{display:none;}
#tab_t{height:25px;border-bottom:1px solid #ccc;}
#tab_t li{float:left; width:80px; height:24px; line-height:24px; margin:0 4px; text-align:center; border:1px solid #ccc; border-bottom:none; background:#f5f5f5; cursor:pointer}
#tab_t .act{ position:relative; height:25px; margin-bottom:-1px; background:#fff;}
#tab_c{border:1px solid #ccc; border-top:none; padding:20px;}




 
  • 选择1
  • 选择2
  • 选择3
  • 选择4
内容1 内容2 内容3 内容4

第二步,实现简单的切换效果

要点1:abc.document.getElementsByTagName("li"):取得abc下面的所有标签为li的元素,返回的是一个元素集合,有数组的一些属性。

要点2:循环,先循环给li加上onclick事件,再onlink事件点击的时候,再循环让所有选项卡的act样式去掉,所有的内容隐藏。然后让所点击的选项及对应内容显示。

要点3:tab_t_li[i].index = i; 在循环时,给选项卡加一个额外的属性并赋值,以做选项卡和内容的对应。





无标题文档

body,ul,li{margin:0; padding:0; font:12px/1.5 arial;}
ul,li{list-style:none;}
.wrap{width:500px; margin:20px auto;}
.hide{display:none;}
#tab_t{height:25px;border-bottom:1px solid #ccc;}
#tab_t li{float:left; width:80px; height:24px; line-height:24px; margin:0 4px; text-align:center; border:1px solid #ccc; border-bottom:none; background:#f5f5f5; cursor:pointer}
#tab_t .act{ position:relative; height:25px; margin-bottom:-1px; background:#fff;}
#tab_c{border:1px solid #ccc; border-top:none; padding:20px;}





 
  • 选择1
  • 选择2
  • 选择3
  • 选择4
内容1 内容2 内容3 内容4

第三步,写成函数。上面的写法只能一个页面用一个选项卡,如果再加一个的话,就需要复制一份,再改很多变量名。

要点:tab_t_li[i][evt] 因为传值的时候是字符串,如果直接写的话就是tab_t_li[i]."onclick"这样话是执行不了的,tab_t_li["onclick"]这样执行没问题。

好了,现在一个页面上就可以有多个切换了,只需要调用函数的时候,写上相应的id名和标签名,事件名称就可以了





无标题文档

body,ul,li{margin:0; padding:0; font:12px/1.5 arial;}
ul,li{list-style:none;}
.wrap{width:500px; margin:20px auto;}
.hide{display:none;}
#tab_t{height:25px;border-bottom:1px solid #ccc;}
#tab_t li{float:left; width:80px; height:24px; line-height:24px; margin:0 4px; text-align:center; border:1px solid #ccc; border-bottom:none; background:#f5f5f5; cursor:pointer}
#tab_t .act{ position:relative; height:25px; margin-bottom:-1px; background:#fff;}
#tab_c{border:1px solid #ccc; border-top:none; padding:20px;}





 
  • 选择1
  • 选择2
  • 选择3
  • 选择4
内容1 内容2 内容3 内容4

希望本文所述对大家Javascript程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/99903.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号