简体   繁体   中英

Jquery Rotating Banner Error

I am a beginner in Jquery I am Trying to make a Rotating Banner With Jquery...

My 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>

And My 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);

};

This Divs are rotating automatic as I need.. But the problem is When I click a button (Circles) it is The rotating banner is moving.. but the next second it is moving as a mad

you can use clearTimeout() like this

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM