2010-09-05 68 views
1

嗨我的網站上有以下代碼,導致div從左側滑出。這工作正常,但是當鼠標離開該區域時,我想讓div立即消失,而不是再次左移動畫。我已經嘗試了許多不同的方式來做這件事,但沒有一件似乎能奏效。我確信有這樣一個簡單的方法。謝謝:)懸停的jQuery動畫效果,在mouseout上即時消失?

$(document).ready(function(){ 
    $("#side-nav a").hover(function(){ 
     $text = $(this).html(); 
     $text = "#" + $text + "-box"; 
     $($text).animate({width:'toggle'},450); 
    }); 
}); 

回答

1

.hover()花費的mouseleave部分(woth一個功能的第二種方法,它運行在mouseentermouseleave,像這樣:

$(function(){ 
    $("#side-nav a").hover(function(){ 
    $("#" + $(this).html() + "-box").animate({width:'toggle'},450); 
    }, function() { 
    $("#" + $(this).html() + "-box").animate({width:'toggle'},0); 
    }); 
}); 

You can give it a try here,這可以讓你仍然使用toggle,但持續時間爲0會觸發即時css更改,而不是動畫。我會考慮使用錨鏈接,而不是使用HTML,如下所示:

<a href="#MyDiv"> 

那麼你的代碼要簡單得多,就像這樣:

$(function(){ 
    $("#side-nav a").hover(function(){ 
    $(this.hash).animate({width:'toggle'},450); 
    }, function() { 
    $(this.hash).animate({width:'toggle'},0); 
    }); 
}); 

您使用的是href="#id"作爲#ID selector直接,如果你還躲在它的指向其它元素在通過JavaScript,這意味着沒有JS的用戶可以得到更好的支持,這會在沒有隱藏內容的情況下優雅地降級。