2015-12-30 113 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

相關問題