简体   繁体   中英

Randomizing effects on jQuery

To keep it small and simple, when clicking a button, all the the divs should slide away in random directions and another set of new divs should be displayed.

Basic demo of what the jQuery code is like:

$(document).ready(function() {
        $("#toggle_value").click(function(){
           $("#div1").show("fast");
           $("#div2").show("fast");
           $("#div3").show("fast");
        });
});

But its all about randomizing the effects. Any solutions?

I would do something like this:

http://jsfiddle.net/8uKt3/13/

 $(document).ready(function() {
        var $div = $('div'),
            pos = [0, 0, 0, 500, 250, 100, 50, -500, -750, -1000, -1500], // Define your numbers
            mypos1,
            mypos2,
            $me;

        $("#toggle_value").click(function(){
            $div.each(function(){
                $me = $(this);

                // Choose a value from each array randomly
                mypos1 = pos[Math.floor(Math.random() * pos.length)];
                mypos2 = pos[Math.floor(Math.random() * pos.length)];

                // animate in a random direction in a random quantitya
                $me.animate({
                    'top' : mypos1,
                    'left': mypos2
                });
            });
        });
    });

You can do something like this, lets say you have 3 possible cases for how the divs might slide away:

var rand = Math.random();
if (rand < .33) {
    // Some animation
} else if (rand < .66) {
    // Some other possible animation
} else {
    // Final animation possibility
}

Algorithm:

  • create an array of 'n' ints
  • shuffle the array
  • in the click function:
    • for each value 'v' in the shuffled array:
      • $('#div' + v).show('fast')

My guess is that you're going to have introduce a delay in the animation using the completion all back on 'effect' for this to look good, but that should be trivial to do

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