This code seems t开发者_Python百科o break the remainder of my code?
function sam() {
$("#animate").children("#box")
.animate({
left: '+=1100'},8000, 'linear', function() {
$("#animate").children("#box").css("left", "0");
sam();
});
}
setInterval(sam());
Sorry about the short response but I kept getting blocked by a stupid quality message
Try to change
setInterval(sam());
to
setInterval(function(){
sam()
}, 1000);
which will trigger sam() every second.Your usage of setInterval is wrong
Also, delete sam()
call in sam()
function.
So final code:
function sam() {
$("#animate").children("#box")
.animate({
left: '+=1100'},8000, 'linear', function() {
$("#animate").children("#box").css("left", "0");
});
}
setInterval(function(){
sam()
}, 1000);
setInterval
needs a second parameter for how often you are going to run the code sam(). but I dont know if you want that, it seems to do that anyway.
function sam() {
$("#animate").children("#box")
.animate({
left: '+=1100'},8000, 'linear', function() {
$("#animate").children("#box").css("left", "0");
sam();
});
}
sam();
should be enought if you want to repeat the animation over and over again, or use setTimeout instead of setInterval.
Set interval will relaunch the code, even if the first run isnt finished, your animation takes 8 seconds, if you say run sam() every 2 second for example you will get a very, very bad result because the codes takes more then 2 seconds to run and you also said that it should rerun itself. I would not use setInterval
at all.
Demo: http://jsfiddle.net/voigtan/tG7Gm/2/
You could use the finished-animation callback to start a new animation. Could you clarify if you want the animation to start when the first one is finished, or just have endless animations on top of each other?
Remove the ()
from where you're passing sam
as the callback. You want to pass the function, not the result of it.
var sam = function() { // Changed this to show functions are variables
$("#animate").children("#box")
.animate({
left: '+=1100'},8000, 'linear', function() { // Not sure about +=
$("#animate").children("#box").css("left", "0");
sam; // Pass the variable, not the result of the function
});
};
sam(); // Call the function the first time.
However, I notice that #box
is an id. So I've extrapolated what I think you want to do and come up with this demo:
var sam = function() { // Changed this to show functions are variables
$("#box").animate({left: $("#animate").width() + 'px'}, 1000, 'linear')
.animate({left: '-' + $("#box").width() + 'px'}, 0, 'linear', sam);
};
sam(); // Call the function the first time.
#animate {
position: relative;
width: 200px;
height: 200px;
background-color: red;
overflow: hidden;
}
#box {
position: absolute;
width: 50px;
height: 50px;
left: 0;
top: 0;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="animate">
<div id="box"></div>
</div>
Or JsFiddle if you prefer: http://jsfiddle.net/Gisleburt/tn8j7w8p/1/
精彩评论