Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

jquery - continuous image swap while mouse is hovering

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...