2013-09-05 35 views
1

我有這樣的代碼:獨特的jQuery做的mouseenter和鼠標離開事件

jQuery(window).one('load',function() { 
    var startopen; 
    var startclose; 
    var delaytime = 350; 
    var togglespeed = 'fast'; 
    jQuery('.hlp').mouseenter(function() { 
     var v = "#" + jQuery(this).parent().parent().attr("id") + " .help"; 
     if(typeof startclose !== undefined) { 
      clearTimeout(startclose); 
     } 
     startopen = setTimeout(function(){ 
      jQuery(v).fadeIn(togglespeed); 
     }, delaytime); 
    }).mouseleave(function(){ 
     var v = "#" + jQuery(this).parent().parent().attr("id") + " .help"; 
     if(typeof startopen !== undefined) { 
      clearTimeout(startopen); 
     } 
     startclose = setTimeout(function(){ 
      jQuery(v).fadeOut(togglespeed); 
     }, delaytime); 
    }); 
}); 

而當鼠標不檢查,看看之前進入的.hlp,則。幫助顯示該特定父,但如果startclose變量被定義。當鼠標離開時,該功能檢查是否定義了startopen,然後設置startclose的超時值。非常直截了當。

我的問題很簡單:當我的mouseenter一個的.hlp和快速切換到附近的.hlp,則startclose從第一的.hlp被激活,當我鼠標離開但隨後當進入第二個.hlp時,超時將被清除。

我正在考慮讓它具有唯一性,因爲我的JS並不是我想叫做的驚人的東西,所以我在尋求讓代碼「更好」的建議。

在此先感謝。 :)

+0

Store中的timerId每個元素上,而不是在全球所有。這可以通過使用.each()或通過使用.data將元素直接存儲在元素上來實現 –

+0

您可以舉個例子嗎?我的jQuery不足以讓我完全理解你的建議。 – BlackBeltScripting

+0

@KevinB你打算回答?還是應該someboby的其他人做呢? –

回答

3

凱文在評論中表達的想法是使用閉包將特定的計時器變量關聯到每個元素。

變化

jQuery('.hlp').mouseenter(function() { 
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help"; 
    if(typeof startclose !== undefined) { 
     clearTimeout(startclose); 
    } 
    startopen = setTimeout(function(){ 
     jQuery(v).fadeIn(togglespeed); 
    }, delaytime); 
}).mouseleave(function(){ 
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help"; 
    if(typeof startopen !== undefined) { 
     clearTimeout(startopen); 
    } 
    startclose = setTimeout(function(){ 
     jQuery(v).fadeOut(togglespeed); 
    }, delaytime); 
}); 

jQuery('.hlp').each(function(){ 
    var startopen, startclose; 
    jQuery(this).mouseenter(function() { 
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help"; 
    if(typeof startclose !== undefined) { 
     clearTimeout(startclose); 
    } 
    startopen = setTimeout(function(){ 
     jQuery(v).fadeIn(togglespeed); 
    }, delaytime); 
    }).mouseleave(function(){ 
    var v = "#" + jQuery(this).parent().parent().attr("id") + " .help"; 
    if(typeof startopen !== undefined) { 
     clearTimeout(startopen); 
    } 
    startclose = setTimeout(function(){ 
     jQuery(v).fadeOut(togglespeed); 
    }, delaytime); 
    }); 
}); 
+0

這解決了這個問題。感謝大家幫助我。 – BlackBeltScripting

+0

我剛剛做到了。感謝@dystroy幫助我適應了stackoverflow的方式! :) – BlackBeltScripting

相關問題