2010-06-03 68 views
0

我得到認真處理jQuery的,但發現自己一遍又一遍的重複代碼...jQuery的簡化代碼(初級)

肯定有寫這個簡單的方法:

$('#more-mcr, #more-hilton, #more-lpool').hide(); 


$('#mcr-hatters').hoverIntent(function() { 
    $('#mcr-hilton').stop().animate({opacity: 0.4}); 
    $('#more-mcr').fadeIn({duration:200}); 
}, function() { 
    $('#mcr-hilton').stop().animate({opacity: 1}); 
    $('#more-mcr').fadeOut({duration:200}); 
}); 

$('#mcr-hilton').hoverIntent(function() { 
    $('#mcr-hatters').stop().animate({opacity: 0.4}); 
    $('#more-hilton').fadeIn({duration:200}); 
}, function() { 
    $('#mcr-hatters').stop().animate({opacity: 1}); 
    $('#more-hilton').fadeOut({duration:200}); 
}); 

$('#lpool-hostel').hoverIntent(function() { 
    $('#more-lpool').fadeIn({duration:200}); 
}, function() { 
    $('#more-lpool').fadeOut({duration:200}); 
}); 

$('#offers-mcr').hoverIntent(function() { 
    $('#offers-lpool').stop().animate({opacity: 0.4}); 
    $('#offers-bham').stop().animate({opacity: 0.4}); 
}, function() { 
    $('#offers-lpool').stop().animate({opacity: 1}); 
    $('#offers-bham').stop().animate({opacity: 1}); 
}); 

$('#offers-lpool').hoverIntent(function() { 
    $('#offers-mcr').stop().animate({opacity: 0.4}); 
    $('#offers-bham').stop().animate({opacity: 0.4}); 
}, function() { 
    $('#offers-mcr').stop().animate({opacity: 1}); 
    $('#offers-bham').stop().animate({opacity: 1}); 
}); 

$('#offers-bham').hoverIntent(function() { 
    $('#offers-lpool').stop().animate({opacity: 0.4}); 
    $('#offers-mcr').stop().animate({opacity: 0.4}); 
}, function() { 
    $('#offers-lpool').stop().animate({opacity: 1}); 
    $('#offers-mcr').stop().animate({opacity: 1}); 
}); 

我'd也想設置hoverIntent的延遲,但我認爲這是不可能的,因爲我目前編寫代碼的方式...?

回答

2

向您想要懸停的各種項目添加一個課程,例如hoverItem。然後,您可以使用$('.hoverItem').hoverIntent(function() ...);一次設置多個項目。鑑於你給出的例子有兩種不同的不透明度,我會創建兩個類。

+0

如果有很多相同的項目,兩個類可能會工作,但如果它將停留在這幾個,ID選擇器可能會更快。 – justkt 2010-06-03 16:41:34

0

您可以創建一個已命名的函數(例如函數myHover(){}),然後在您的.hoverIntent引用中將其作爲.hoverIntent(myHover)。另外,如果您希望兩個ID具有相同的附加功能,請考慮使用Multiple Selector