把上面的 js 包成 jQuery 的外掛, 方便以後使用..
$.fn.HitEvent = function(ops) {
ops = jQuery.extend({
onHit: null,
onMiss: null
}, ops);
return this.each(function() {
var self = $(this);
$("body").click(function (e) {
var target = e.target;
if (self.attr('id') == target.id || $(target).parents("#" + self.attr('id')).length > 0) {
if (ops.onHit) ops.onHit(self);
} else {
if (ops.onMiss) ops.onMiss(self);
}
});
});
};
使用方式...
$("#div-1").HitEvent({
onHit: function(e) {
e.css('background-color', '#fff8f8');
},
onMiss: function(e) {
e.css('background-color', '#f8fff8');
}
});
$("#div-3").HitEvent({
onHit: function(e) {
e.css('background-color', '#3ff8f8');
}
});