我的代码运行良好...
但有一点我无法解决:
当我mouseover
图像时,循环开始很好,但在随后的鼠标移动中,它开始变化越来越快......
var Image = new Array("//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP");
var Image_Number=0;
var Image_Length= Image.length;
function change_image(num){
Image_Number = Image_Number + num;
if(Image_Number > Image_Length)
Image_Number = 0;
if(Image_Number < Image_Length)
document.slideshow.src = Image[Image_Number];
return false;
Image_Number = Image_Length;
}
function auto () {
setInterval("change_image(1)", 1000);
}
&#13;
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseover="auto()" />
&#13;
答案 0 :(得分:0)
每mouseover
您重新分配一个全新的区间™,导致多个功能同时运行。
name
是obsolete HTML5 attribute - 另请参阅img tag @ W3.org "change_image(1)"
... setInterval
或setTimeout
tigger eval
内的字符串。这很糟糕。应该使用真正的函数名称:setInterval(functionName, ms)
num
return
声明mouseenter
事件(而不是mouseover
)这是重拍:
var images = [
"//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP"
];
var c = 0; // c as Counter ya?
var tot = images.length;
var angryCat = false;
// Preload! Make sure all images are in tha house
for(var i=0; i<tot; i++) {
var im = new Image();
im.src= images[i];
}
function changeImage() {
document.slideshow.src = images[++c%tot];
}
function auto() {
if(angryCat) return; // No more mouse enter
angryCat = true;
setInterval(changeImage, 1000);
}
&#13;
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseenter="auto()" />
&#13;
使用++c % tot
来实现增量和循环
angryCat
布尔标志有助于知道auto()
已经启动(鼠标在那里!),在这种情况下,它将return;
(退出)该函数,防止在其上创建额外的重叠间隔随后的mouseenter(这是你的主要问题)。
此外,我建议让你的JS远离HTML,所以不要使用JS属性事件
onmouseenter="auto()"
为您的图片id="myimage"
分配ID并使用JS:
document.getElementById("myimage").addEventListener("mouseenter", auto, false);