jQuery:动画图像连续左右移动

时间:2015-08-13 20:59:19

标签: javascript jquery

我试图让我的图像从左到右连续前后移动,但它一直向左移动,永远不会正确返回。我按照我发现的代码,似乎无法找到我做错的事。

http://jsfiddle.net/7kmmxeeg/1/



$(document).ready(function() {
	function firstleft() {
		$(".block.first").animate({"left": "-=100px" }, 1500, "swing", firstright);
	}
	function firstright() {
		$(".block.first").animate({"right": "+=100px" }, 1500, "swing", firstleft);
	}
	firstleft();
});

div.container {
	position:relative;	
	background-color:rgba(149, 187, 206, 0.36);
	height:700px;
	overflow:hidden;
}

div.block {
	height:200px;
	width:200px;
	background-color:blue;
	overflow:hidden;
}

div.block.first	{
	position:absolute;
	left:100px;
	top:300px;
	overflow:hidden;
}

div.block.second {
	position:absolute;
	top:10px;
	left:500px;
	background-color:green;
	overflow:hidden;
}

div.block.third {
	position:relative;
	top:350px;
	left:500px;
	background-color:red;
}

div.block.first img {
	background-size:cover;
	width:400px;
	margin-left:-100px;
}

div.block.second img {
	background-size:cover;
	width:400px;
	margin-left:-100px;
}

div.block.third img {
	background-size:cover;
	width:400px;
	margin-left:-100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
	<div class="block first">
		<img src="img/first.jpg">	
	</div>
	
	<div class="block second">
		<img src="img/second.jpg">
	</div>
	
	<div class="block third">
		<img src="img/third.jpg">
	</div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

答案:在right函数中将left更改为firstright()

function firstleft() {
    $(".block.first").animate({"left": "-=100px" }, 1500, "swing", firstright);
}
function firstright() {
    $(".block.first").animate({"left": "+=100px" }, 1500, "swing", firstleft);
}

Updated Fiddle