【发布时间】:2019-01-28 15:15:44
【问题描述】:
我正在为我的视频创建一个播放和暂停按钮。超时完成后,该视频将消失,因为它将关闭 .active 类,这会将其恢复为 0 不透明度。我已将此绑定到onmousemove为此,我正在使用 clearTimeout。
我无法让它工作。播放按钮会闪烁,因为类不断添加。
这是我的功能
const togglePlay = (...args) => playButton.classList.toggle(...args);
var timer = null;
vid.onmousemove = function(){
if (timer!= null){
clearTimeout(timer);
}
else {
togglePlay("active");
timer = setTimeout(() => {
togglePlay("active");
stopTime();
}, 2000);
}
}
我已经阅读了多个其他有同样问题的帖子。我尝试实现这个:How to use clearTimeout
我从另一个帖子中得到了 timer=null。
我还尝试了另一种方法,即禁用 togglePlay。这确实达到了我想要的效果,但是通过测试控制台日志,它仍然在后台触发了很多。
我就是这样做的
var timer = null;
vid.onmousemove = function(){
if (timer != null){
console.log("TimedOut");
}
else {
//right here is the mistake, this is not a timer
timer = togglePlay("active");
setTimeout(() => {
togglePlay("active");
timer = null;
console.log("setTimeout");
}, 2000);
}
}
这种代码虽然违背了 clearTimeout 的目的。所以我的问题真的。我在 setTimeout 上做错了什么?
【问题讨论】:
-
为什么要使用 onmousemove 来清除超时?我很困惑为什么你在这里实际上需要超时。是2秒后暂停播放吗?或者在鼠标移动时暂停播放?抱歉,我对您到底想要实现什么感到有点困惑
-
这就像您在观看 YouTube 视频,甚至是 Netflix。当您将鼠标移到窗口上时,将出现暂停按钮。但是当您停止移动鼠标时,它会在设定的时间后淡出。这就是我想要达到的目标。它只会在 2 秒内切换一个类。
-
mousemove只要鼠标在移动就会持续触发;你可能想要mouseenter。 (或者,如果您需要捕捉元素内的运动,debounce 事件。) -
我知道它确实在移动,但我想知道的是如何完全阻止它发射。我确实阅读了 debounce,但我发现很难理解它,所以我尝试先自己构建它。
标签: javascript