Jquery旋转横幅错误

时间:2013-10-15 13:47:25

标签: javascript jquery html

我是Jquery的初学者 我正试图用Jquery做一个旋转横幅......

我的Index.html

<html>
<head>
<title>Automatic Rotating banner</title>
<script src="jquery.min.js"></script>
<script src="java.js"></script>
<style type="text/css">
a {
background:#fff;
width:30px;
text-align:center;
padding:5px 0px;
display:inline-block;
border-radius:50%;
border:1px solid #c5c5c5;
cursor:pointer;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}
.a {
background:#000;
color:#fff;
}
</style>
</head>
<body style="background:#f5f5f5;" onload="rotate(1) ;">
<div style="width:300px;height:40px;background-color:#fff;border:1px solid #e5e5e5;overflow:hidden;box-shadow:1px 1px 2px rgba(0,0,0,0.1);">
<div style="height:40px;width:1500px" id="box">
<div style="width:300px;text-align:center;padding:10px 0px;display:inline-block;float:left;">First</div>
<div style="width:300px;text-align:center;padding:10px 0px;display:inline-block;float:left;">Second</div>
<div style="width:300px;text-align:center;padding:10px 0px;display:inline-block;float:left;">Third</div>
<div style="width:300px;text-align:center;padding:10px 0px;display:inline-block;float:left;">Fourth</div>
<div style="width:300px;text-align:center;padding:10px 0px;display:inline-block;float:left;">First</div>
</div>
</div>
<br/>
<a onclick="rotate(1)" id="a1">1</a> <a onclick="rotate(2)" id="a2">2</a> 
<a onclick="rotate(3)" id="a3">3</a> <a onclick="rotate(4)" id="a4">4</a>
<br/>
<span id="demo"></span>
</body>
</html>

我的java.js

function rotate(num){

$("#demo").html( num);

var nu = num  * 300 -300;
$("#box").animate({ marginLeft: -nu}, 600 );
$("a").removeClass('a', {duration:500});
$("#a" + num).addClass('a', {duration:500});

setTimeout(function() { rotate(num + 1) }, 3000);

};

这个Divs根据我的需要自动旋转.. 但问题是 当我点击一个按钮(圆圈)时,旋转的横幅正在移动..但是下一秒它正在疯狂地移动

1 个答案:

答案 0 :(得分:0)

你可以像这样使用clearTimeout()

var timeout;
function rotate(num){
    $("#demo").html(num);
    clearTimeout(timeout);//clear the timer
    var nu = num  * 300 -300;
    $("#box").animate({ marginLeft: -nu}, 600 );
    $("a").removeClass('a', {duration:500});
    $("#a" + num).addClass('a', {duration:500});
    //num<4?num+1:1 if num is outside the actual number return to the first one
    timeout=setTimeout(function() { rotate(num<4?num+1:1) }, 3000);
};    

http://jsfiddle.net/xXnpc/2/