2012-07-12 80 views
0

我有一個div來從頂部到另一個div的底部進行動畫製作。我目前正在玩w/mouseenter/leave和JS動畫w/easing,它的原始狀態是up/top。我想懸停/ mouseenter,並讓它向下移動,如果我mouseleave /懸停關閉下來。當我再次懸停時,它會回到頂部/開始。多個懸停實例jQuery

我最初使用的mouseenter/leave顯然不會做我所需要的,因爲我希望狀態在mouseleave時保持不變。那麼什麼功能最適合這種需求呢?我仍然在學習術語,並在如何更好地提出問題方面陷入困境。

代碼:

function init() { 
     mouseenter: function(){ 
      $(".ltrP").stop(true, true).animate({ 
       marginTop:"170px" 
      }, 
      { 
       duration: 1000, 
       easing: "easeOutBounce" 
      }); 
     }, 
     mouseleave: function(){ 
      $(".ltrP").stop(true, true).animate({ 
       marginTop: "0px" 
      }, 
      { 
       duration: 1000, 
       easing: "easeInBounce" 
      }); 
     } 
    }); 
} 
window.onload = init; 

回答

1

我已經編輯了一段代碼,請參閱說明評論:

$(document).ready(function(){ // Runs when document is loaded 

    $(".ltrP").mouseenter(function(){ // Mouseenter event on the given object (.ltrP) 
     var goTo = $(this).css("marginTop") == '0px' ? 170 : 0; // When the current margin-top is 0px animate to 170px, otherwise animate it back to 0px 
     $(this).stop(true,false).animate({ // Changed the stop(true, true) to stop(true, false), looks nicer in my opinion 
      marginTop: goTo // Animate to the just set variable 
     }, 1000); 
    }); 

}); 

而且在這裏看到一個演示:http://jsfiddle.net/hnDmt/

(而寬鬆「easeInBounce」不是爲我工作,所以我刪除它(也許一個jQuery UI緩動?))

+0

謝謝Lumocra!我選擇了這個答案,因爲它與其他情況一起工作似乎非常靈活,並且爲將來的學習需求/提示而着名。 – Commandrea 2012-07-12 18:49:31

1

你可以重寫你的代碼是這樣的:

$(document).ready(function(){ 
    init(); 
}); 
function init() { 
    $.hover(function(){ 
     $(".ltrP").stop(true, true).animate({ 
      marginTop:"170px" 
     }, 
     { 
      duration: 1000, 
      easing: "easeOutBounce" 
     }); 
    }, 
    function(){ 
     $(".ltrP").stop(true, true).animate({ 
      marginTop: "0px" 
     }, 
     { 
      duration: 1000, 
      easing: "easeInBounce" 
     }); 
    }); 
} 
1

有很多方法可以做到這一點。也許最簡單的概念化是向動畫項目添加一個類。你想寫兩個獨立的mouseenter函數。

對於第一個功能,觸發您的向下動畫,並添加一個類到輸入的項目。稱之爲「飄落」類或者明顯的東西。

然後,寫第二個mouseenter函數。當包含該類的項目是鼠標中心時,將其設置爲動畫並刪除該類。

忘掉jQuery hover。這只是mouseenter/mouseleave的包裝。它可能會導致問題。 jQuery文檔警告它。單獨編寫mouseenter和mouseleave函數通常會更好,特別是當您嘗試做一些棘手的事情時更是如此。