2016-11-26 50 views
2

我想要一个视频播放器全屏,并且我想让控件在mousemove上显示。由于没有mousestop我刚启动了一个计时器,如果它完成,它将隐藏工具。jQuery mousemove自己触发

问题 - 由于我怀疑回调的性质,效果不断在显示和隐藏之间来回切换。该类mouseMoving在CSS中添加display: block !important,当它被删除,theControls返回到它的原始的CSS这是display: none !important

$('#theDiv').mousemove(

     function() 
     { 
      //When the mouse is moving, add the class which adds display: block !important 
      $('#theControls').addClass('mouseMoving'); 

      // Clear the timer each time the mouse moves, so that if the mouse doesnt move for a full 2 seconds, 
      // hide the controls by removing the afforementioned class. 

      clearTimeout(timer); 

      var timer = setTimeout(

      function() 
      { 
       $('#theControls').removeClass('mouseMoving'); 
      }, 

      2000); 
     } 
    ); 

事实上,如果你走在全屏幕和移动鼠标,该控件将出现,然后隐藏,然后开发工具将显示类mouseMoving正在不断被追加和删除,即使我不再移动鼠标,。这将无限期地继续下去,或者直到鼠标再次移动,然后循环重复。

+0

你为什么叫'clearTimer'上'timer'定义之前呢?你不应该在闭包之外定义'timer',所以你可以这样做吗? – ahitt6345

+0

而且,你的意思是'clearTimer'或'clearTimeout'?因为除非你定义了'clearTimer',否则不存在。 – ahitt6345

+0

@ ahitt6345我的意思是'clearTimeout'抱歉,把它改了。 –

回答

0

看看我的小提琴。 https://jsfiddle.net/Lfzt5u9j/37/

基本上采取!important属性可在CSS你display:none !important;部分,并把它放在display:block.mouseMoving。你必须这样做的原因是因为你的css的ID部分中的任何内容都会覆盖你的css的CLASS部分。如果你没有得到它,请用我的小提琴弄乱或提问:D

然后,让你的Js看起来像我的小提琴。

var timer; 
$('#theDiv').mousemove(function() { 
    //When the mouse is moving, add the class which adds display: block !important 
    //console.log($('.mouseMoving')); 
    $('#theControls').addClass('mouseMoving'); 

    // Clear the timer each time the mouse moves, so that if the mouse doesnt move for a full 2 seconds, 
    // hide the controls by removing the afforementioned class. 
    clearTimeout(timer); 
    timer = window.setTimeout(function() { 
     $('#theControls').removeClass('mouseMoving'); 
    }, 2000); 
}); 

实际上,为了覆盖所有!important你有你的情况做的是使类选择更具体。

一样,如果你对mouseMoving类是

.mouseMoving { 
    display:block !important; 
} 

将其更改为:

div#theControls.mouseMoving { 
    display:block !important; 
} 
+0

我无法从中删除'!important',否则控件永远不会隐藏。代码中还有一些其他的代码将内联样式放置在'display:block'工具上,这就是为什么我必须使用'!important'来覆盖它的原因。我正在建立一个已经建立的代码库,所以这就是为什么它很困难。 –

+0

当你使用'$('。mouseMoving')。removeClass();它原来是这样。它在第一次隐藏后再也不会出现。 –

+0

真的吗?当你在不带参数的情况下执行'removeClass'时,它只会删除与该元素相关的所有类。 – ahitt6345