您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);
});
});
沒有使用'toggle()'這種方式已棄用? – j08691
另外需要注意的是,在開始下一個'.animate()'之前,您可能需要調用'.stop(true,true)'。 –
@ j08691儘管它處於「不推薦」類別,但我看不到任何棄用通知。除命名衝突外,我也看不到任何棄用的原因。 –