【发布时间】:2011-07-29 22:52:45
【问题描述】:
我正在努力了解如何将闭包与 jQuery 事件函数结合使用。
我目前的问题是在屏幕上圆形形状,使它们在鼠标悬停时停止并淡出,并在鼠标移出时淡出并重新启动。我必须使用图像映射来创建圆形鼠标悬停敏感区域。虽然动画效果很好,但我无法按照我的意愿使用鼠标悬停功能上的闭包。
鉴于此设置:
(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 以所有元素为目标,而不仅仅是主动悬停的元素。我将如何使用闭包来避免使用索引或类似的解决方法?
非常感谢!
【问题讨论】:
标签: javascript jquery events closures