2013-03-23 58 views
4

我正在學習jQuery的基礎知識,並且當我發現mouseleave和mouseenter動作時,我開始懷疑我應該在哪裏放置mouseleave動作?哪一個更正確,並且會一直工作?Mouseleave在mouseenter內部或外部?

$(document).ready(function(){ 
    $('div').mouseenter(function(){ 
     $(this).fadeTo('fast','1'); 
     $(this).mouseleave(function(){ 
      $(this).fadeTo('fast','0.25'); 
     }); 
    }); 
}); 

或者也許這個1更好?

$(document).ready(function(){ 
    $('div').mouseenter(function(){ 
     $(this).fadeTo('fast','1'); 
     }); 
     $('div').mouseleave(function(){ 
      $(this).fadeTo('fast','0.25'); 
     }); 
}); 

回答

3

您的第二個選項更正確,它應該始終有一個單獨的事件設置。每次觸發mouseenter時,您的第一個選項都會添加一個新的mouseleave事件,從而導致發生很多附加事件。所以使用:

$('div').mouseenter(function() { 
    $(this).fadeTo('fast', 'fast'); 
}); 
$('div').mouseleave(function() { 
    $(this).fadeTo('fast', '0.25'); 
}); 

其實.hover(handlerIn, handlerOut)其實有一些很好的速記。

$('div').hover(
    function() { $(this).fadeTo('fast', 'fast'); }, 
    function() { $(this).fadeTo('fast', '0.25'); } 
); 
+0

當你打我2秒 – 2013-03-23 03:27:02

+0

謝謝;) btw。看看fadeTo參數'fast'+'fast'的第一個功能是多麼愚蠢:D 我正在編寫codecademy曲目,所以稍後我可能會了解.hover。無論如何thx;) – 2013-03-23 03:34:57