2012-12-21 41 views
0

我有一個上下滑動div的切換功能。但是我怎樣才能讓它在mouseleave上切換marginTop -200?在mouseleave div上切換marginTop

我應該爲mouseleave有一個單獨的函數嗎?

$(document).ready(function() { 
    $('.menu-item-40').toggle(

    function() { 
     $('#slidenav').animate({ 
      marginTop: '0' 
     }, 500); 
    }, function() { 
     $('#slidenav').animate({ 
      marginTop: '-200px' 
     }, 500); 
    }); 
});​ 
+0

沒有使用'toggle()'這種方式已棄用? – j08691

+0

另外需要注意的是,在開始下一個'.animate()'之前,您可能需要調用'.stop(true,true)'。 –

+0

@ j08691儘管它處於「不推薦」類別,但我看不到任何棄用通知。除命名衝突外,我也看不到任何棄用的原因。 –

回答

0

div選擇使用mouseleave事件。然後申請我爲你創建的自定義功能toggleMargin(我用+ -20px,而不是你的所需值)

<div id="div"></div> 

// CUSTOM TOGGLEMARGIN FUNCTION 
var t = true; 
jQuery.fn.toggleMargin=function(){ 
    var lastmargin = $(this).css('margin-top').replace("px", ""); 
    var newMargin; 
    if(t){ 
    newMargin = parseInt(lastmargin)+20; 
    t=false; 
    } 
    else{ 
    newMargin = parseInt(lastmargin)-20; 
    t=true; 
    } 
    // Now apply the margi-top css attr 
    $(this).css('margin-top', newMargin); 
} 

// LET'S TOGGLE MARGIN ON YOUR DIV 
$('#div').mouseleave(function(){ 
    $(this).toggleMargin();  
});​ 

TEST

* UPDATE 22/12/12 *

由於我只提供代碼試試這個:

TEST2

// CUSTOM TOGGLEMARGIN FUNCTION 
var t = true; 
jQuery.fn.toggleMargin=function(){ 
var lastmargin = $(this).css('margin-top').replace("px", ""); 
var newMargin; 
if(t){ 
    newMargin = parseInt(lastmargin)+20; 
    t=false; 
} 
else{ 
    newMargin = parseInt(lastmargin)-20; 
    t=true; 
} 
// Now apply the margi-top css attr 
$(this).css('margin-top', newMargin); 
} 

$('#slidenav').mouseleave(function(){ 
     $(this).toggleMargin();    
}); 

$('.menu-item-40').click(function(){ 
     $('#slidenav').toggle(function() { 
     $(this).animate({marginTop: '0'}, 500); 
     });   
}); 
+0

在哪個div選擇器上添加mouseleave? – user681061

+0

在你想更改邊距的那個上。看着你的代碼,我猜是'menu-item-40'。或者您可以按F12並選擇div以獲取其「id」。 – anmarti

+0

如果您沒有設法獲得它,請添加更多'html'代碼並更好地解釋您想實現的目標,並嘗試使我的代碼適應您的要求。 – anmarti