2012-07-28 55 views
2

我有一個簡單的懸停動畫;我分開mouseentermouseleave函數來定義mouseleave上的contidion。如果該聚合是真的,禁用mouseleave函數,但我不能得到這個條件的工作,JavaScript忽略我的條件,並運行mouseleave函數。如何使用if hasClass條件禁用jQuery mouseleave事件? //懸停動畫

Here is jsFiddle.

的jQuery:

$('.bigBox').mouseenter(function() { 
    $('.trigger').stop().animate({'left':'-50px'},222); 
    $('.bigBox').stop().animate({'left':'-1px'},222); 
}); 


var holdCondition = $('#hold').hasClass('selected'); 
//tried to disable mouseleave here but didnt work 

if (!holdCondition) {//if #hold has not class selected 
    $('.bigBox').mouseleave(function() { 
     $('.trigger').stop().animate({'left':'-1px'},222); 
     $('.bigBox').stop().animate({'left':'-111px'},222); 
    }); 
} 


$('.option').click(function(){ 
    $('.option').removeClass('selected'); 
    $(this).addClass('selected'); 
}); 

HTML:

<div class="bigBox"> 
    <span class="trigger">X</span> 

    <span class="option selected">A</span> 
    <span class="option">B</span> 
    <span id="hold" class="option">Hold</span> 
</div> 

CSS:

.bigBox { 
    position:fixed; top:10%; width:100px; height: 20px; 
    left:-111px; border:1px solid #000; padding-left:5px; 
} 
.trigger { 
    position:fixed; top:10%; width:20px; height: 20px; 
    left:-1px; border:1px solid #000; text-align:right; padding-right:5px; 
} 
.option { margin:0 5px; cursor:pointer; } 
.selected { color:#f00; } 

+0

我編輯了自己的代碼檢查該http://jsfiddle.net/Bvr9B/14/ – 2012-07-28 19:03:41

回答

3

holdCondition將只運行一次,而不是你要檢查它的每一個.mouseleave()。 試試這個。

Here is jsFiddle.

$('.bigBox').mouseleave(function() { 
     var holdCondition = $('#hold').hasClass('selected'); 

     if (!holdCondition) {//if #hold has not class selected 
      $('.trigger').stop().animate({'left':'-1px'},222); 
      $('.bigBox').stop().animate({'left':'-111px'},222); 
     } 
    }); 
+0

它的外觀像我做了簡單的錯誤鮑勃。感謝您指出了這一點。 – 2012-07-28 19:22:36

+0

不客氣。 :) – Bob 2012-07-28 19:24:16

+0

解決方法的好主意+1 – Fizzix 2014-03-19 02:37:13

0

'seleced'何時應用於ID爲'hold'的元素? 我懷疑發生與用戶交互,不一定在頁面加載?

你寫這個問題的方法:

if (!holdCondition) {//if #hold has not class selected 
    $('.bigBox').mouseleave(function() { 

的鼠標離開被若不holdCondition在頁面加載定義

你想要的是檢查holdCondition鼠標離開內:

$('.bigBox').mouseleave(function() { 
    if (!holdCondition){ 
     $('.trigger').stop().animate({'left':'-1px'},222); 
     $('.bigBox').stop().animate({'left':'-111px'},222); 
    } 
});