题目:
实现选项卡,点击01跳转到01选项卡的内容,点击02跳转到02选项卡的内容。
1.主体Body部分
做一个基础的结构,设置行内默认样式。
z-index 代表的是我们显示的一个层级关系
<body>
<ul class="ul1">
<li style="background-color: #ffd700">01</li>
<li>02</li>
<li>03</li>
</ul>
<div class="Box">
<div style="z-index: 1">选项卡1的内容</div>
<div>选项卡2的内容</div>
<div>选项卡3的内容</div>
</div>
</body>
2.CSS基础样式
相应的地方也做了标注,应该没什么问题,接下来就是Script部分了
*{
list-style-type: none;
margin: 0;
padding: 0;
font-size: 15px;
}
.ul1 li{
width: 73px;
height: 29px;
float: left; /*添加左浮动*/
line-height: 29px; /*垂直居中*/
cursor: pointer; /*将指针改为小手*/
text-align: center;/*水平居中*/
margin-right: 10px;/*外边距 间隔*/
background-color: #dddddd;
}
.Box{
width: 400px;
height: 200px;
position: relative; /*相对定位 父元素*/
clear: both; /*清除浮动*/
}
.Box div{
width: 400px;
height: 200px;
background-color: #ffd700;
position: absolute; /*绝对定位 子元素*/
}
3.JQ部分
涉及到一些基础的语法知识,这里给大家做个介绍:
- css() 设置样式
- siblings() 获取同级元素,兄弟选择器
- index() 获取元素下标
- eq() 下标选择器
$(function () {
$('.ul1 li').click(function () {
$(this).css('background-color','#ffd700').siblings().css('background-color','#dddddd');
$('.Box div').eq($(this).index()).css('z-index','1').siblings().css('z-index','0');
})
})
4.测试
我们打开页面
-
点击02
2.成功实现
点击03也是如此,大功告成!~~~
5.完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选项卡</title>
<style>
*{
list-style-type: none;
margin: 0;
padding: 0;
font-size: 15px;
}
.ul1 li{
float: left;
width: 73px;
height: 29px;
line-height: 29px;
cursor: pointer;
text-align: center;
margin-right: 10px;
background-color: #dddddd;
}
.Box{
width: 400px;
height: 200px;
position: relative;
clear: both;
}
.Box div{
width: 400px;
height: 200px;
background-color: #ffd700;
position: absolute;
}
</style>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"</script>
<script>
$(function () {
$('.ul1 li').click(function () {
$(this).css('background-color','#ffd700').siblings().css('background-color','#dddddd');
$('.Box div').eq($(this).index()).css('z-index','1').siblings().css('z-index','0');
})
})
</script>
</head>
<body>
<ul class="ul1">
<li style="background-color: #ffd700">01</li>
<li>02</li>
<li>03</li>
</ul>
<div class="Box">
<div style="z-index: 1">选项卡1的内容</div>
<div>选项卡2的内容</div>
<div>选项卡3的内容</div>
</div>
</body>
</html>