我试图让我的头了解如何使用与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