我有如下图像
coolimg.1.jpg
我想1
用以下数组循环:
[2,5,8,11,14,17,20,23,26,29]
...mouseover
延迟 1 秒开启
我应该如何开始?
我有如下图像
coolimg.1.jpg
我想1
用以下数组循环:
[2,5,8,11,14,17,20,23,26,29]
...mouseover
延迟 1 秒开启
我应该如何开始?
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
到目前为止,这还不完整,但它可以提供一个开始的地方:
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);
});
}
干得好。
这将为 id 中的元素设置动画imgId
。动画仅在 1 秒后开始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);
}
这个版本有更好的代码和标记分离:
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);