如何使用ifClass条件禁用jQuery mouseleave事件? //悬停动画

时间:2012-07-28 18:52:55

标签: javascript jquery hover jquery-animate conditional-statements

我有一个简单的悬停动画;我分离了mouseentermouseleave函数来定义mouseleave上的contidion。如果那个cocontidion是真的;禁用mouseleave函数,但我不能让这个条件工作,javascript忽略我的条件并运行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; }

2 个答案:

答案 0 :(得分: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);
        }
    });

答案 1 :(得分:0)

'seleced'何时被应用于id为'hold'的元素? 我怀疑用户交互会发生这种情况,不一定是在页面加载上吗?

你写这个的方式:

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

如果不是holdCondition,则在pageload上定义

你想要的是在mouseleave中检查!holdCondition:

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