2010-02-12 60 views
1

下面是HTML & jQuery代碼我有:JQuery的動畫延遲問題

HTML我有:

<div class="announcement"> 
    <img id="imgBanner" style="cursor: pointer;" onmouseover="showPopup();" /> 
</div> 
<div id="divArrow" class="arrow"> 
    <img id="imgExpandContract" style="cursor: pointer;" alt="Arrow" border="0"onmouseover="showPopup();" /> 
</div> 
<div id="window"> 
    <!-- some html content acting as a fly-out --> 
</div> 

JS代碼:

var imgBanner = "xyx.png"; 
var imgArrowExpand = "xyx.png"; 
var imgArrowContract = "xyx.png"; 
var isDone = false; 

function showPopup() { 
    try { 
     var imgWidth = $("#imgExpandContract").width(); 
     var posX = document.getElementById("imgExpandContract").offsetLeft + imgWidth; 
     if (!$("#window").is(":animated")) { 
      $("#window").animate({ left: posX }, 800, 'easeOutSine', 
           function() { 
            isDone = true; 
            $("#imgExpandContract").attr("src", imgArrowContract); 
            $("#window").bind("mouseenter", function() { $("#window").bind("mouseleave", function() { closePopup(); }); }); 
           } 
      ); 
     } 
    } 
    catch (error) { 
     //disable the banner, arrow images 
     document.getElementById("imgBanner").style.visibility = 'hidden'; 
     document.getElementById("imgExpandContract").style.visibility = 'hidden'; 
    } 
} 

function closePopup() { 
    try { 
     if (isDone) { 
      var posY = $("#window").width(); 
      $("#window").animate({ left: -posY }, 600, 'linear', 
          function() { 
           isDone = false; 
           $("#imgExpandContract").attr("src", imgArrowExpand); 
           $("#window").unbind("mouseenter"); 
           $("#window").unbind("mouseleave"); 
          } 
      ); 
     } 
    } 
    catch (error) { 
     //disable the banner, arrow images 
     document.getElementById("imgBanner").style.visibility = 'hidden'; 
     document.getElementById("imgExpandContract").style.visibility = 'hidden'; 
    } 
} 
目前我有2個問題

  1. 當我將鼠標移出#window div時,在調用mouseleave之前有一個小的延遲。我怎樣才能讓它消失?它有點保持幾毫秒,然後注視老鼠葉子。

  2. mouseleave事件有時不會觸發......偶爾會發生,但會發生。我必須在#window div上移動我的鼠標並移回(基本上必須執行兩次)?任何人都可以讓我知道爲什麼會發生這種情況,我能如何處理?

除了在JQuery中使用animate()之外,還有更好的解決方案嗎?對所有/任何建議感到高興。我正在嘗試使用div內的內容執行飛出/幻燈片效果。

非常感謝您的幫助

回答

3

嗯,我不知道,這將SOVE您所陳述的問題,但也有一些事情是要幫助你的代碼的整體。例如,我的第一印象是:

「好吧他使用jquery ......等我以爲他在用jQuery ...... WTF?」。

  1. 爲什麼要用getElementById?使用$('#myid')
  2. 爲什麼要用style.visibility?使用$(selector).css('visibility', value);
  3. 不要使用元素屬性綁定事件...使用jQuery $(selector).hover(openPopup, closePopup);

好與出路是你當鼠標離開不能解僱你肯定鼠標離開該地區?我的意思是你確定div的尺寸比你想象的要大一些嗎?如果不是這種情況,可能很簡單就是執行該功能所需的時間,或者可能是因爲它沒有完成動畫製作(例如,isDone = false)。在我看來,並非試圖檢測某些事情是否已完成動畫,我只需要撥打$(element).stop(true);即可在其端點停止動畫,然後繼續處理其他動畫。這應該是非常安全的。另外我相信,如果你用false來調用它,或者完全忽略參數,它會將它完全停在它所在的位置......允許您從當前位置激活出來的動畫,而無需計算位置。

另外,我不知道這是什麼真正的樣子,但它可能是你甚至需要使用animate您可以使用內置在像slide什麼效果的一個 - 你可能婉TTO看着那些以及。

+0

對於$(element).stop(true)爲+1;我解決了我的問題,雖然我的問題不同:) – Dimskiy 2010-08-05 17:28:36