2015-12-30 86 views
0

我想在使用它之前将函数定义为变量,显然然后我可以使用$(this).off('mouseleave',fadeOutt)来关闭它,并且$(this).on(' mouseleave',fadeOutt)将其重新打开。为什么我不能在.on中调用我的函数?

为什么这个工作:

var fadeDarl = function(){   
$("#darl").on({ 
    mouseenter: function(){ 
     $("#bgimg1").stop(true,true).fadeIn(200); 
}, 
    mouseleave: function() { 
     $("#bgimg1").stop(true,true).fadeOut(200); 
} 
}); 
}; 

fadeDarl(); 

但不是这样的:

var fadeInn = function() { 

    $("#bgimg1").stop(true,true).fadeIn(200); 
}; 
var fadeOutt = function() { 

    $("#bgimg1").stop(true,true).fadeOut(200); 

}; 

    var fadeDarl = function(){   
$("#darl").on({ 
    mouseenter: fadeInn(), 
    mouseleave: fadeOutt() 
}); 
}; 

fadeDarl(); 
+0

**删除'()'**。代码:'$(“#darl”)。on; { – Tushar

回答

2

在此代码:

var fadeDarl = function(){   
$("#darl").on({ 
    mouseenter: fadeInn(), 
    mouseleave: fadeOutt() 
}); 
}; 

当你把括号fadeInn后,调用该函数和将其返回值分配给mouseenter

您真正想要做的是将函数本身指定为mouseenter,以便可以在指定事件触发时稍后调用该函数。
所以,只需删除这些括号,它会按预期工作。

,如果你来自何方功能不能按引用传递语言这可能混淆你,但在JavaScript函数是first-class objects

1

你需要,而不是通过调用它的功能:

变化

$("#darl").on({ 
    mouseenter: fadeInn(), 
    mouseleave: fadeOutt() 
}); 

$("#darl").on({ 
    mouseenter: fadeInn, 
    mouseleave: fadeOutt 
}); 
1

删除括号。您正在调用该函数并返回值,而不是将该函数分配给该事件。

mouseenter: fadeInn(), 
mouseleave: fadeOutt() 
1

你传递的功能无法正常工作本身评估/结果,它应该是:

$("#darl").on({ 
    mouseenter: fadeInn, 
    mouseleave: fadeOutt 
}); 
1

谁说你不能只是改变fadeInn()来fadeInn

1

当你做mouseenter: fadeInn()然后你用fadeIn()的返回值绑定mouseenter事件。
因此,该函数在绑定时只会被调用一次,然后在mouseenter上它将尝试调用返回值,即未定义。
因此,而不是结合的返回值,你应该做

mouseenter: fadeInn 

,将做的工作

0

老实说你应该使用合适的工具合适的工作。这是css的目的。另外,您将获得由gpu而不是cpu加速的动画硬件,并且您不会锁定js的单个线程。唯一一次我赞成js对css的偏好是当我需要挂钩到动画生命周期中的事件,或者需要像补间那样更复杂的动画时。

#darl figure { 
 
    opacity: 0; 
 
    visibility: hidden; 
 
    transition: .2s all; 
 
    display: inline-block; 
 
} 
 

 
#darl:hover figure { 
 
    opacity: 1; 
 
    visibility: visible; 
 
}
<div id="darl"> 
 
    <p>I am a div. there are many like me but this one is me</p> 
 
    <figure id="bgimg1" class="fade_wrapper"> 
 
    <img src="http://lorempixel.com/100/100" /> 
 
    <figcaption>lorem pixel yall</figcaption> 
 
    </figure> 
 
</div>

+0

我需要使用jquery,因为我正在做一些可以扩展的东西,然后停止监听mouseenter/leave然后当你关闭它会重新开始......我可能已经能够使用addClass和removeClass来做到这一点...... – Ming

相关问题