JQuery样式操作、click事件以及索引值-选项卡应用示例

2020-05-27 18:03:40易采站长站整理

.box{
width: 200px;
height: 200px;
background-color: gold;
}
.col01{
background-color: green;
}
</style>
</head>
<body>
<input type="button" name="" value="切换样式" id="btn">
<div class="box">div元素</div>
</body>
</html>

索引值-选项卡

有时候需要获得匹配元素相对于其同胞元素的索引位置,此时可以用index()方法获取。


var $li=$('.list li ').eq();
alert($li.index());//弹出


<ul class="list">
<li>1</li>
<li>2</li>
..............
<li>6</li>
</ul>

得到索引值


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var $li=$('.list li');
// alert($li.length);
alert($li.eq(3).index());
var s=$li.filter(".myli").index();
alert(s);
})
</script>
</head>
<body>
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li class="myli">5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>
</body>
</html>

选项卡的制作,点击事件之后,当前点击的事件加上样式,其他统计的元素,去掉样式,关键代码


$(this).addClass('current').siblings().removeClass('current');
var num=$(this).index();
$div.eq($(this).index()).addClass('active').sibling().removeClass('active');

完整:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.btns input{
width: 100px;
height: 40px;
background-color: grey;
border: 0;
}
.btns .current{
background-color: gold;
}
.cons div{
width: 500px;
height: 300px;
background-color: gold;
display: none;/*整体都不显示了*/
text-align: center;
line-height: 300px;
font-size: 30px;
}
.cons .active{
display: block;
}
</style>