gpt4 book ai didi

javascript - 鼠标离开时停止每个循环

转载 作者:行者123 更新时间:2023-11-28 17:59:32 36 4
gpt4 key购买 nike

我有一个带有数据属性的 anchor (图像对象),在 mouseenter 上我想循环浏览这些图像,然后在 mouseleave 上我希望结束循环。

这是我到目前为止所得到的,但似乎在 shouldRotateImages 变量更改之前完整的 each 运行,即使有延迟。所以我对现在能做什么感到有点迷失。

var shouldRotateThumbnails = false;
$(document).on('mouseenter', '#videos-list a', function () {
shouldRotateThumbnails = true;
rotateThumbnails($(this));
});

$(document).on('mouseleave', '#videos-list a', function () {
shouldRotateThumbnails = false;
});

function rotateThumbnails(video) {
var thumbnails = video.data('thumbnails');
var image = video.find('img');
$.each(thumbnails, function (k, v) {
if (!shouldRotateThumbnails) {
return false;
}
setTimeout(function () {
image.attr('src', v);
}, (300 * k));
});
}

最佳答案

通过使用@squint的建议设法做到了这一点。

var t;
$(document).on('mouseenter', '#videos-list a', function () {
var imageKey = 0;
var thumbnails = $(this).data('thumbnails');
var image = $(this).find('img');
t = setInterval(function () {
image.attr('src', thumbnails[imageKey]);
imageKey += 1;
if (imageKey == thumbnails.length) {
imageKey = 0;
}
}, 300);
});
$(document).on('mouseleave', '#videos-list a', function () {
clearInterval(t);
var image = $(this).find('img');
var thumbnail = $(this).data('original-thumbnail');
image.attr('src', thumbnail);
});

关于javascript - 鼠标离开时停止每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43810702/

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