I have an image like the following
coolimg.1.jpg
I would like to loop the 1
with the following array:
[2,5,8,11,14,17,20,23,26,29]
...on mouseover
with a delay for 1 second
How should I get started?
var imgs = [2,5,8,11,14,17,20,23,26,29]
, last = imgs.length
, count = 0
, timer
, img_name
;//var
function cycleImage(){
if(count++ < last){
img_name = 'coolimg.' + imgs[count] + '.jpg';
// do something with image
timer = setTimeout(changeImage, 1000);
}
}
function resetImage(){
count = 0;
clearTimeout(timer);
}
var $element = $('element');
$element
.on ('mouseover', cycleImage)
.off('mouseout' , resetImage)
;//var
This is by far not complete but it could give a place to start:
var imageRoller=function(){
this.myNumbers=[2,5,8,11,14,17,20,23,26,29];
this.currentIndex=0;
this.timerID=0;
this.onMouseover=function(){
//do something
var currentID="coolimg."+
this.myNumbers[this.currentIndex]+
".jpg";
//increase the current index
this.currentIndex++;
if(this.currentIndex>=
this.myNumbers.length){
this.myNumbers=0;
}
//do something again in 1 second
me=this;
setTimeout(function(){
me.onMouseover();
},1000);
}
this.onMouseout=function(){
// stop doing something agqain in 1 second
clearTimeout(this.timerID);
}
//attach the mouseover and out events:
var me = this;
document.getElementById("someImg")
.addEventListener("mouseover", function(){
me.onMouseover.call(me);
});
}
Here you go.
This will animate the element with the id in imgId
. The animation only starts after 1 second on mouseover
.
HTML
<img id="myImg" onmouseover="imgId = this.id; timer = setTimeout(animate, 1000);" onmouseout="stopAnimation();" src="coolimg.1.jpg" />
JS
var myImages = [1, 2, 3, 5]
var img_index = 0;
var timer;
var imgId = "myImg";
// Start animation
function animate() {
me = document.getElementById(imgId);
me.src = "coolimg." + myImages[img_index] + ".jpg"
img_index++;
if (img_index == myImages.length){
img_index = 0;
}
timer = setTimeout(animate, 1000);
}
function stopAnimation() {
clearTimeout(timer);
}
This version has better separation of code and markup:
var coolimg = {
images : [2,5,8,11,14,17,20,23,26,29],
position : 0,
mouseOver : false,
target : document.getElementById('coolimg')
}
coolimg.target.addEventListener('mouseenter',function(){
coolimg.mouseOver = true;
});
coolimg.target.addEventListener('mouseleave', function(){
coolimg.mouseOver = false;
});
setInterval(function(){
if (coolimg.mouseOver) {
coolimg.position = (coolimg.position+1)%coolimg.images.length;
coolimg.target.src = 'coolimg.'+coolimg.images[coolimg.position]+'.jpg';
}
}, 1000);
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.