问题描述:

i have an idea but i'm not quite sure how to execute it.

i want have an image that when the mouse hovers over it, it quickly changes to a random image, and changes pretty quickly to a new random image. it keeps going until you take your mouse off it, and then it stops on the last image. when you roll over it again it should start to swap around again. it would sort of be like a slot machine effect. i don't need them to spin around, just change in place.

i could really use some pointers on how to accomplish this. i don't really know where to start. i know the basics of how to swap a background image of a div on a mouseover, but that's about all i know.

thanks

EDIT: http://cargocollective.com/ Look at the Cargo logo in the top left corner of the screen. that's the effect i'm looking for, except it would stop on the last image instead of resetting.

网友答案:

JQuery's .hover() can use a function for the mouseover and mouseout states, so it's trivial to do something like

html:

<img id="swap" src="http://lorempixum.com/200/200/sports" alt=""/>

jquery:

var images = ["http://lorempixum.com/200/200/sports",
              "http://lorempixum.com/200/200/food",
              "http://lorempixum.com/200/200/abstract",
              "http://lorempixum.com/200/200/people",
              "http://lorempixum.com/200/200/technics",
              "http://lorempixum.com/200/200/city"
             ],//store a bunch of images in an array
    i = 0,//counter
    $swap = $("#swap"),//only get the object once
    swapper;//setup a var for setInterval

function swapImg(){
    i = i % images.length;//keep i under the array length
    $swap.attr("src",images[i]);// change image src        
    i++;
}

$swap.hover(function(){//mouseover
    swapper = setInterval(swapImg,10);//call function every 10ms
},function(){//mouseout
    clearInterval(swapper);//stop calling the image swapper
});​

here's a demo

I'm using http://lorempixel.com/ for the dummy images, but they'll return a random image each time you request one, so this displays more images than are in the array, and that makes it load funky sometimes.

网友答案:

Every jQuery event has a callback function, so on mouseover you could start a callback function A that calls function B that calls function A, etc. On mouseout, break the infinite callback loop.

相关阅读:
Top