站外推广营销方案,wordpress清除所有评论,南京网站制作招聘,海外网盟渠道在大家在网上平常浏览网页的时候#xff0c;想必各位都会看到选项卡功能#xff0c;在这里给大家详解一下用原生js、jQuery如何来写一些基本的选项卡
话不多说#xff0c;先给各位看一下功能图#xff1a; 好了#xff0c;下边开始写代码了#xff1a;
HTML代码#x…在大家在网上平常浏览网页的时候想必各位都会看到选项卡功能在这里给大家详解一下用原生js、jQuery如何来写一些基本的选项卡
话不多说先给各位看一下功能图 好了下边开始写代码了
HTML代码 ul
li classclickred/li
liblue/li
liyellow/li
/ul
div classbox
div classshow/div
div/div
div/div
/div CSS代码: *{
margin: 0;
padding: 0;
}
ul{
overflow: hidden;
/*注意父级元素塌陷详情见博客*/
}
ul li{
width: 100px;
height: 30px;
float: left;
border: 1px solid #000;
list-style: none;
border-right: none;
text-align: center;
line-height: 30px;
cursor: pointer;
}
ul li:last-child{
border-right: 1px solid #000000;
}
.box{
position: relative;
}
.box div{
width: 304px;
height: 300px;
position: absolute;
display: none;
}
.box div:first-child{
background-color: red;
}
.box div:nth-child(2){
background-color: blue;
}
.box div:last-child{
background-color: yellow;
}
.box .show{
display: block;
}
.box .hide{
display: none;
}
.click{
background-color: #ccc;
} 基本样式的设置原生JS写法 var liAll document.querySelectorAll(li);//获取要操作的元素
var divAll document.querySelectorAll(.box div);//获取被操作的跟随元素
for (var i 0;iliAll.length;i ) { //for循环为每一个元素添加点击事件
liAll[i].index i; //作用域的问题如果for循环使用let声明则不需要该行代码
liAll[i].onclick function () {
for (var j 0;jliAll.length;j ) {
liAll[j].className ;//将所有被操作的元素的背景色消失
divAll[j].className hide;//将所有被操作的元素全部隐藏
}
this.className click;//当前被点击的元素背景色改变
divAll[this.index].className show;//将所有被操作的元素跟随显示
}
} jQuery写法
引入jQuery文件 网址https://www.bootcdn.cn/jquery/ script srchttps://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js/script $(li).each(function (index , ele) {//each循环遍历。得到所有的li index代表li的下表ele元素
$(this).click(function () {//$(this) 表示当前点击的元素
$(this).addClass(click);
$(this).siblings().removeClass(click);
$(.box div:eq( index )).css({display:block}); //eq 根据each循环得出index的所引值 取对应的div显示
$(.box div:eq( index )).siblings().css({display:none}); //对应的div隐藏
});
}); 源代码下载地址https://github.com/Mere-scholar/tab
如果您有看不明白的地方可以留言咱们共同交流
前端知识更新的很快继续努力吧
更多专业前端知识请上
【猿2048】www.mk2048.com