效果图:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;padding: 0;
}
ul li{
list-style: none;
}
#box{
width:500px;
height:150px;
overflow: hidden;
border: 1px solid black;
}
#box ul{
position: relative;
}
#box ul li{
position: absolute;
top:0px;
width: 200px;
height: 150px;
}
#box ul li:nth-child(1){
left: 0px;
}
#box ul li:nth-child(2){
left: 50px;
}
#box ul li:nth-child(3){
left: 100px;
}
#box ul li:nth-child(4){
left: 150px;
}
#box ul li:nth-child(5){
left: 350px;
}
#box ul li:nth-child(6){
left: 400px;
}
#box ul li:nth-child(7){
left: 450px;
}
#box ul li div{
float: left;
height: 150px;
}
#box ul li div:first-child{
width: 50px;
}
#box ul li img{
width: 150px;
height: 150px;
}
</style>
</head>
<body>
<div id="box">
<ul>
<li>
<div style="background-color: red">红色1</div>
<div><img src="img/01.jpg"></div>
</li>
<li>
<div style="background-color: orange">橙色1</div>
<div><img src="img/02.jpg"></div>
</li>
<li>
<div style="background-color: yellow">黄色1</div>
<div><img src="img/03.jpg"></div>
</li>
<li>
<div style="background-color: green">绿色1</div>
<div><img src="img/04.jpg"></div>
</li>
<li>
<div style="background-color: cyan">青色1</div>
<div><img src="img/05.jpg"></div>
</li>
<li>
<div style="background-color: blue">蓝色1</div>
<div><img src="img/06.jpg"></div>
</li>
<li>
<div style="background-color: purple">紫色1</div>
<div><img src="img/07.jpg"></div>
</li>
</ul>
</div>
</body>
</html>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
//左移右移的参数使用当前点击对象,不是下标
//右移
function moveRight($obj) {
let baseLeft = parseInt($obj.css("left"));
$obj.nextAll().each(function (i) {
let left = baseLeft+(i+1)*50+150;//计算每个li最终left值。
if(parseInt($(this).css("left"))<left){
$(this).animate({
"left":left
},500);
}
});
}
//左移
function moveLeft($obj) {
let $li = $("li:first").nextUntil($obj.next());
$li.each(function (i) {
let left = (i+1)*50;//计算每个li最终left值。
if(parseInt($(this).css("left"))>left){
$(this).animate({
"left":left
},500);
}
});
}
$(function () {
$("li").click(function () {
let index = $('li').index(this);
if(parseInt($(this).css("left"))>index*50){
moveLeft($(this));
}else{
moveRight($(this));
}
});
});
</script>