2016-11-26 77 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