$ `(function(){
$('.left li').click(function(){ //获取li的焦点以及设置单机事件函数
$(this).addClass('active').siblings().removeClass('active'); //当单机事件激活时,添css“active”;同时匹配上一同胞元素删除样式“active”;
var _index= $(this).index(); //定义一个变量_index并赋值当前的元素的DOM位置
var top=-_index*300; //定义一个变量top,让其与变量_index相乘,从而计算出新位置top。
$('.all').animate({ //获取带all class的焦点,并设置0.5s动画,改变元素定位的top值。
top:top
},500)
})
})
jQuery遍历:siblings() 获得匹配集合中每个元素的同胞,通过选择器进行筛选是可选的。
index() 方法返回指定元素相对于其他指定元素的 index 位置。这些元素可通过 jQuery 选择器或 DOM 元素来指定。注意:如果未找到元素,index() 将返回 -1。
<html>
<head>
<meta charset="UTF-8"/>
<title></title>
<script src="js/jquery-3.2.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
$('.left li').click(function(){
$(this).addClass('active').siblings().removeClass('active');
var _index= $(this).index();
var top=-_index*300;
$('.all').animate({
top:top
},500
)
})
})
</script>
</head>
<body>
<div id="box">
<ul class="left">
<li class="active">新闻</li>
<li>新闻</li>
<li>新闻</li>
<li>新闻</li>
</ul>
<div class="area">
<ul class="all">
<li>啦啦啦啦啦啦</li>
<li>llalalla</li>
<li>啦啦11441啦</li>
<li>啦啦啦啦啦啦21</li>
</ul>
</div>
</div>
<style type="text/css">
*{
list-style: none;
padding: 0px;
margin: 0px;
background: none;
}
body{
padding: 100px;
}
#box{
background: rgba(0,0,0,0.1);
display: block;
float: left;
height: 300px;
overflow: hidden;
}
.left{
width: 300px;
display: block;
float: left;
background: #FFF;
}
.left li{
width: 25%;
float: left;
height: 30px;
text-align: center;
}
.active{
background: #222;
color: #FFF;
}
.area .all li{
height: 300px;
}
.area{
margin-top: 30px;
position: relative;
}
.area .all{
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</body>
</html>