gpt4 book ai didi

javascript - jQuery 为每个元素分配超时事件处理程序

转载 作者:行者123 更新时间:2023-11-29 09:53:45 25 4
gpt4 key购买 nike

对我来说很有趣。我有一个视频播放器,其控件在悬停时显示。最初,我使用 CSS 完成此操作,但不得不将策略更改为 javascript 以便与浏览器全屏 api 一起玩(顺便说一下,这意味着您总是在视频上徘徊)。

我的新方法是为添加类的视频容器设置 mousemove 的事件处理程序,并设置超时以将其删除,如果已设置超时,则将其清除。这非常有效,但逻辑无法扩展到多个玩家。

TLDR:如何扩展我的逻辑以扩展到多个视频容器? time 变量的范围需要包含在每个元素事件中,但也需要在处理程序之外,以便它可以从一个事件清除到下一个事件(在同一元素上)。

谢谢你的帮助——这些逻辑题对我来说总是很难的。

这是一个 jsFiddle example .您会注意到,当您将悬停限制在一个元素上时效果很好,但当您扩展到页面上的其余元素时就会出现问题。

HTML:

<div class="cont">

<div class="controls">controls</div>
</div>

JavaScript:

var time;

$('body').on('mousemove', '.cont', function(){

var thiis = $(this);

if (time){

clearTimeout(time);
}

thiis.addClass('showControls');

time = setTimeout(function(){

thiis.removeClass('showControls');
}, 2000);
});

最佳答案

您可以使用 jQuery 的数据方法来存储时间变量,该方法可以在您的每个元素上存储数据。

$('body').on('mousemove', '.cont', function(){

var thiis = $(this),
// get the time from the data method
time = thiis.data("timer-id");

if (time){
clearTimeout(time);
}

thiis.addClass('showControls');

var new_time = setTimeout(function(){
thiis.removeClass('showControls');
}, 2000);

// save the new time
thiis.data("timer-id", new_time);
});

关于javascript - jQuery 为每个元素分配超时事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887196/

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