简体   繁体   中英

How to randomise and mimic a rollover in jquery?

I have a JQuery script which acts as a simple image rollover with a nice fade effect.

Here is a test version of the current script in action - http://fi-testing.co.uk/SO/rubix-cube.html

As you can see, there are 9 blocks, the client wishes for the rollovers to occur randomly (without a hover) to kind of create a ripple/pulsating effect.

How would this be achieved with either JQuery or php?, and would It be possible that hovering over breaks the randomisation and acts as normal?

Sorry if any of this is unclear.

Thanks for any help.

Dan

Without going too much into your code, you can create randomness by Math.random()

so if you have an array of your cube entires, indexed 0 - 8, you may use

var randomNumber = parseInt( Math.random() * 9 );
var randomCube = cubes[randomNumber];

you can use setInterval to get this to repeat once in every x ms

function randomlyChangeCubes() { ... }

...

setInterval( randomlyChangeCubes, 2000 );

you can use jQuery trigger to invoke the hover effect manually, but I'd say it'd be more readable to extract the code you have in hover to a function which you call both from hover and from randomlyChangeCubes .

All that being said... doing this entirely randomly probably won't make it look rippling/pulsating...

Things you would need:

setTimeout/setInterval = call you 'effect' function at a set time random number = use this to call the required element randomly eg #box1, #box2 etc.

I think thats it - should be fairly straightforward.

It can be tricky to accomplish a cool looking randomness. The Math.random() method produces pseudo-random values from the uniform distribution (ie, all values in the range have the same probability) and that will not look nice.

I'm not an expect and I cannot tell you what distribution will yield better results but you can try the normal and poisson distributions:

http://www.ciphersbyritter.com/JAVASCRP/BINOMPOI.HTM (see page source for code)

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