我想创建一个功能,如果用户将光标悬停在图像上,图像就会发生变化并循环显示我指定的一堆图像。我之前已经实现了这一点,但我没有使用悬停,而是使用点击,这相当容易。
简而言之,如何使图像在 mouseenter 上循环?
我的代码:
var n = 0;
var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];
var image = $('#himg');
image.on('mouseenter', function change() {
var newN = n+1;
if (newN >= images.length) { newN = 0 };
image.attr('src', images[n]);
image.fadeOut(200, function () {
image.attr('src', images[newN]);
image.fadeIn();
n = newN;
});
});
最佳答案
mouseenter当鼠标移动到 dom 元素的范围内时仅触发一次。当鼠标最终离开时,会触发 mouseleave
事件。您可以使用它来启动一个间隔来循环浏览您的图像。
var n = 0;
var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];
var image = $('#himg');
var intervalId;
var intervalTimeout = 200;
image.on('mouseenter', function change() {
intervalId = setInterval(function() {
var newN = n+1;
if (newN >= images.length) { newN = 0 };
image.attr('src', images[n]);
image.fadeOut(200, function () {
image.attr('src', images[newN]);
image.fadeIn();
n = newN;
});
}, intervalTimeout);
});
image.on('mouseleave', function() {
clearInterval(intervalId);
});
关于javascript - 如何使mouseenter函数循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44932959/