mousemove事件
接下来,我们通过jQuery插件形式来实现放大镜效果,当鼠标移动到small对象上方时,就会在large对象中显示大图的对应位置,这就涉及到mousemove事件了,所以,我们需要实现mousemove事件的监听方法。
实现jquery.imagezoom.js插件:
(function($) { $.fn.imageZoom = function(options) {
var defaults = {
scaling: 0.3,
small :"small",
large : "large",
magnify:"magnify"
};
options = $.extend(defaults, options),
native_width = 0,
native_height = 0,
current_width = 0,
current_height = 0,
magnify="."+options.magnify;
small="."+options.small;
$small=$(small);
large="."+options.large;
$large=$(large);
$(magnify).mousemove(function(e) {
var image_object = new Image();
image_object.src = $small.attr('src');
if(!+[1,]) {
native_height = image_object.height;
native_width = image_object.width;
}
else {
image_object.onload = function() {
image_object.onload = null;
native_height = image_object.height;
native_width = image_object.width;
}
}
current_height = $small.height();
current_width = $small.width();
var magnify_offset = $(this).offset();
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
if (mx < $(this).width() && my <$(this).height() && mx > 0 && my > 0) {
$large.fadeIn(100);
} else {
$large.fadeOut(100);
}
if ($large.is(":visible")) {
var rx = Math.round(mx / $small.width() * native_width - $large.width() / 2) * -1,
ry = Math.round(my / $small.height() * native_height - $large.height() / 2) * -1,
bgp = rx + "px " + ry + "px",
px = mx - $large.width() / 2,
py = my - $large.height() / 2;
$large.css({
left: px,
top: py,
backgroundPosition: bgp
});
}
//}
});
};
})(jQuery);
注释:当鼠标移动到magnify对象中,我们需要获取鼠标在magnify中的相对坐标位置,这里我们把相对坐标定义为(mx,my),通过上图我们知道相对坐标等于(pageX – offsetLeft, pageY – offsetTop)。
现在,我们已经获取鼠标在magnify对象中的坐标值,接下来,需要获取对应大图的相应坐标,这里我们把大图的对应坐标定义为(rx,ry),我们可以通过比例关系获取(rx,ry)的值。










