2015-08-31 26 views
0

我遇到了JQuery mouseout函數和setTimeout問題。帶有鼠標輸出功能的JQuery超時問題

我想實現的是,當我懸停一個元素時,它會改變背景。當我離開那個元素(所以mouseout被觸發)後,背景應該在1秒後回到原始狀態。

.mouseover(function(){ 
    changeBackground(); 
}) 
.mouseout(function(){ 
    //setTimeout(function() { 
    goBack(); 
    //}, 1000); 
}); 

但是,如果我去掉了超時功能(這是我想達到的目標),即使我:

如果我使用下面的代碼,goBack功能只有當我離開這個元素稱爲不要離開那個元素,goBack函數被調用。

任何幫助或建議,以避免這個問題?

回答

3

這是因爲事件的冒泡的所以使用的鼠標懸停和鼠標移開,而不是mouseentermouseleave或使用hover一樣,

.hover(function(){ 
    changeBackground(); 
},function(){ 
    setTimeout(function() { 
     goBack(); 
    }, 1000); 
}); 

.mouseenter(function(){ 
    changeBackground(); 
}) 
.mouseleave(function(){ 
    setTimeout(function() { 
     goBack(); 
    }, 1000); 
}); 

jQuery.mouseenter的文檔,

mouseenter事件不同從mouseover處理 事件冒泡的方式。如果在此示例中使用mouseover,那麼當 鼠標指針移到Inner元素上時,處理程序將觸發 。這通常是不受歡迎的行爲。另一方面,mouseenter事件只在鼠標進入綁定的元素時觸發其處理程序,而不是後代。所以在這個例子中,當鼠標進入Outer元素而不是Inner元素時,觸發器被觸發。

更新,這裏有超時的問題,你需要明確這是改變的背景上的mouseenter像

function changeBackground() { 
 
    $('#content').addClass('yellow'); 
 
} 
 

 
function goBack() { 
 
    $('#content').removeClass('yellow'); 
 
} 
 
var t=null;//clear timeout variable 
 
$(function() { 
 
    $('#content').mouseenter(function() { 
 
    clearTimeout(t);// clear previous timeouts 
 
    changeBackground(); 
 
    }).mouseleave(function() { 
 
    t=setTimeout(function() { //set new timeouts 
 
     goBack(); 
 
    }, 1000); 
 
    }); 
 
});
#content { 
 
    background-color: #eee; 
 
    padding: 20px; 
 
    cursor: pointer; 
 
} 
 
.yellow { 
 
    background-color: #ffff00 !important; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="content"> 
 
    Lorem ipsum doner inut 
 
</div>

+0

我都嘗試之前超時,但問題仍然存在。如果我輸入或懸停一個元素並取消超時註釋,1秒後goBack被調用,即使我不離開 –

+0

順便說一下,即使使用懸停功能,我也想暫停。這就像我試圖實施的評級系統,所以我想等一秒鐘後再回到保存的評級。 –

+0

你可以在這裏嘗試你自己的代碼https://github.com/stestisa/star_rating,並看到問題仍然存在 –