jQuery写一个简单的选项卡

前言

       这次通过jQuery的方法来写一个小小的选项卡功能,通过jQuery实现起来也是十分的简单。

直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}

div {
border: 1px solid #000;
width: 800px;
height: 400px;
margin: 0 auto;
position: relative;
}

.ch {
top: 320px;
left: 650px;
position: absolute;
}

.ch>li {
display: inline-block;
width: 20px;
height: 20px;
background-color: #ccc;
margin-right: 10px;
}

img {
width: 100%;
height: 400px;
display: none;
}

.current {
display: block;
background-color: red !important;
}
</style>

<body>
<div>
<ul class="imgs">
<li><img class="current"
src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2489492398,1961915359&fm=26&gp=0.jpg"
alt=""></li>
<li><img src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1287814793,457485829&fm=26&gp=0.jpg"
alt=""></li>
<li><img src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1501075685,574908757&fm=11&gp=0.jpg"
alt=""></li>
<li><img src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3662540589,314327097&fm=11&gp=0.jpg"
alt=""></li>
</ul>
<ul class="ch">
<li class="current"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
$(function () {
$('.ch>li').mouseenter(function () {
$(this).addClass('current').siblings().removeClass('current');
// 给当前操作的小方块添加样式,其他的兄弟小方块去除样式
var index = $(this).index();
// 获取当前是第几个小方块,用来确定是第几张图片
$('.imgs>li>img').eq(index).addClass('current').parent().siblings().children()
.removeClass('current');
// 给对应的图片添加样式,其他的图片删除样式
})
})
</script>
</body>

效果图:

总结

  • 写这个选项卡思路很简单,但是在布局的时候没有考虑好导致在给img标签删除样式的时候会比较麻烦,需要先找到父级li,然后找到他的兄弟,再找到他们的儿子,下次要注意避免出现这种情况。
-------------本文结束感谢您的阅读-------------