gpt4 book ai didi

javascript - 如何使mouseenter函数循环

转载 作者:行者123 更新时间:2023-12-03 03:56:15 25 4
gpt4 key购买 nike

我想创建一个功能,如果用户将光标悬停在图像上,图像就会发生变化并循环显示我指定的一堆图像。我之前已经实现了这一点,但我没有使用悬停,而是使用点击,这相当容易。

简而言之,如何使图像在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com