我試圖讓我的頭瞭解如何使用與jQuery事件函數有關的閉包。jQuery關閉和事件函數(mouseover,mouseout,...)
我目前的問題是圓形在屏幕上的形狀,使他們停下來,在鼠標懸停和淡入淡出,並重新開始鼠標。我必須使用imagemaps來創建一個圓形的鼠標懸停敏感區域。雖然動畫工作正常,但我很難在鼠標懸停功能上使用閉包,因爲我希望它是。
鑑於此設置:
(function($){
$.fn.xyz = function(option) {
// override defaults with specified option
option = $.extend({}, $.fn.xyz.option, option);
return this.each(function(index, element) {
// run works fine.
function run(index) {
$(".ball:eq(" + index + ")").css({top: 500).startAnimation({ top: -500}, 1000, "linear", (function (i) {
return function() {
run(i);
}})(index));
}
//1 this version works great but I don't like the .parent().parent() especially as the animation requires
// just the ball I hover over gets the opacity assigned
$("area").mouseover(
function() {$(this).parent().parent().css('opacity', 0.5);}
);
//2 this version makes all balls transparent on page load
$("area").mouseover(
(function (activeElement) {
$(activeElement).css('opacity', 0.5);
})(this)
);
//3 this version makes all balls transparent on the first mouse over event
$("area").mouseover(
(function (activeElement) {
return function() {
$(activeElement).css('opacity', 0.5);
}
})(this)
);
//4 also this version affecs all balls and not just the one that is mouse overed
var activeBall = $(this);
$("area").mouseover(function() {
$(activeBall).css('opacity', 0.5);
}).mouseout(function() {
$(activeBall).css('opacity', 1);
});
run(index);
});
},
$.fn.xyz.option = {};
})(jQuery);
爲什麼版本2,3和4的目標的所有元素,而不只是它正在積極上空盤旋之一。我將如何利用閉包來避免使用索引或類似的解決方法?
非常感謝!
謝謝!你的回答解釋了爲什麼在第二種情況下所有元素在頁面加載時都設置爲不透明度0.5。我想出了爲什麼所有的元素都是針對性的。我應該用 $(本).find( 「區域」)鼠標懸停( (函數(activeElement){ 恢復功能(){$ (activeElement)的.css( '不透明',0.5);} }) ); 僅針對當前元素的區域。在上面的代碼中,它將它分配給所有的元素。完美的感覺,我的壞! – Novazembla 2011-04-05 14:54:50
沒問題。請記住點擊空白記號以接受答案(表明問題已解決。) – Zirak 2011-04-05 15:02:52