我有这个id在我的html代码:
<div id="me">
<img src="Me.JPG" alt="Me" width="450" height="450" alt="picture" align="right"/>
</div>
如何在鼠标停留在图片上后每3秒更换一次图片,
和回到原来的图片一旦鼠标出来?
您可以创建一个函数,每3秒更改一次图像。然后,当您将鼠标移到图像上时,调用该函数并启动计时器。当鼠标离开图像时,清除计时器。
var img = document.getElementById( "me" ).getElementsByTagName( "img" )[0];
var images = ["Me.JPG", "new image path", "..."];
var i = 1;
var timer;
function change() {
img.src = images[i];
if ( ++i >= images.length ) {
i = 0;
}
timer = setTimeout( change, 3000 );
}
img.onmouseover = function() {
timer = setTimeout( change, 3000 );
};
img.onmouseout = function() {
img.src = images[0];
clearTimeout( timer );
};
这里有一个JsFiddle快速解决方案的链接:http://jsfiddle.net/jJBEu/2/
var img = document.getElementById('me').getElementsByTagName('img')[0],
index = 0,
sources = [
'http://icons.iconarchive.com/icons/iconka/social-treat/128/yumtube-icon.png',
'http://icons.iconarchive.com/icons/iconka/social-treat/128/sweeter-icon.png',
'http://icons.iconarchive.com/icons/iconka/social-treat/128/facebow-icon.png'
],
timer;
img.addEventListener('mouseover', swapImages, false);
img.addEventListener('mouseout', function(){
clearTimeout(timer);
img.src = sources[0];
}, false);
function swapImages(event, setindex){
index = index == (sources.length - 1) ? 0 : index + 1;
timer = setTimeout(function(){
img.src = sources[index];
swapImages();
}, 3000);
}
编辑修复一个愚蠢的错误,我检查数组索引长度没有减去1。
html:
<img src="Me.JPG" alt="Me" width="450" height="450" alt="picture" align="right"
onmouseover="animate(this)" onmouseout="stopanimation()" />
javascript: /* globals */
var animTimer = null;
var animImg = null;
var images = [new Image(), new Image(), new Image(), new Image(), new Image(),new Image()];
var imgIndex = 0;
/* pre-load images in browser cash */
images[0].src = "Me.JPG";
images[1].src = "anim1.gif";
images[2].src = "anim2.gif";
images[3].src = "anim3.gif";
images[4].src = "anim4.gif";
images[5].src = "anim5.gif";
/* animation */
function animate(img){
if (typeof img != 'undefined'){animImg = img;}
imgIndex += 1;
if (imgIndex>images.length-1){imgIndex=1;}
animImg.src=images[imgIndex].src;
animTimer = setTimeout(animate, 3000);
}
function stopanimation(){
clearInterval(animTimer);
animImg.src = images[0].src;
}
就像,只给myImg
的img
和id
(或任何你想要的):
var img_arr = ["img1.png", "img2.png", "img3.png"],
img_index = 0,
interval_id = 0,
div = document.getElementById("me"),
img = document.getElementById("myImg");
div.onmouseover = function () {
interval_id = window.setInterval(function () {
if (img_index === (img_arr.length - 1)) {
img_index = 0;
}
img.src = img_arr[img_index++];
}, 3000);
};
div.onmouseout = function () {
window.clearInterval(interval_id);
};