开发者

I want to make some divs race

So maybe this is kind of juvenile, but I'm still learning Jquery. I've got a couple of DIVs (50x50px absolutely positioned) and this code makes them move across the screen. I want to make it so if you click on the green box it reduces the interval thereby moving faster. Obviously I'm doing something wrong here, I'm just not sure what.

$(document).ready(function(){
  var greenSpeed = 300;
  var redSpeed = 300;
  var redLeft = $('#red').offset().left;
  setInterval(function() {
    $('#red').css('left', ++redLeft);
    }, redSpeed);
  var g开发者_运维百科reenLeft = $('#green').offset().left;
  setInterval(function() {
    $('#green').css('left', ++greenLeft);
    }, greenSpeed);
  $('#green').click(function() {--greenSpeed});
});


Your updates to the timer intervals after you've already started the timer will have no effect. Perhaps you should keep the timer interval constant, and then instead of always just adding 1 to the positions, vary the size of the increment.

That is, "redSpeed" and "greenSpeed" would start off at 1, and then you'd add those on each iteration to "redLeft" or "greenLeft". Clicks should simply increase the "speed" variables by 1 (or 2 or whatever).


The reason the first one didn't work is that setInterval was being passed the value stored in greenSpeed and not a pointer to that variable. Because of this, subsequent updates to greenSpeed had no effect. In your 2nd bit of code, you are calling setTimeout repeatedly. Each time it is called it is passed the current value stored in greenSpeed, thereby using the new value after a click.


This works like you want it...

$(function(){

    var greenSpeed = 300;
    var redSpeed = 300;

    var redLeft = $('#red').offset().left;

    function raceRed() {

        setInterval(function() {
            $('#red').css('left', ++redLeft);
        }, redSpeed);

    }

    $('#red').click(function() {
        --redSpeed;
        raceRed();
    });

    raceRed();

    var greenLeft = $('#green').offset().left;

    function raceGreen() {

        setInterval(function() {
            $('#green').css('left', ++greenLeft);
        }, greenSpeed);

    }

    $('#green').click(function() {
        --greenSpeed;
        raceGreen();
    });

    raceGreen();

});


Okay... so I figured out how to do it, but if someone could explain WHY that would be helpful.

var greenLeft = $('#green').offset().left;
function moveGreen() {
    setTimeout(moveGreen, greenSpeed);
    $('#green').css('left', ++greenLeft);
}
moveGreen();
$('#green').click(function() {greenSpeed-=20});

My guess is that setInterval only checks colorSpeed once when it's first called, so even if I decrement the speed counter it doesn't matter. Is there a way to do it w/ setInterval, or is a recursive setTimeout call the only way?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜