实现原理
首先,我们讲解一下放大镜效果的实现方式:
方法一:准备一张高像素的大图,当鼠标放到原图上,加载显示大图的对应位置。
方法二:对原图片进行放大,也就是调整原图的长和宽。
上面我们介绍了通过两种方式实现放大镜效果,接下来,我们将以上的两种方式应用到我们的jQuery插件中。
首先,我们需要一个img元素显示原图对象,还需要一个容器作为显示框;显示框里面存放大图对象。当鼠标移动到原图上时,通过对大图进行绝对定位来显示对应的部位,实现类似放大镜的效果。
接下来,让我们定义Index.html页面,具体实现如下:
放大镜效果 ![]()
![]()
css样式:
.magnify {width: 200px; margin: 50px auto; position: relative;}
.large {width: 175px; height: 175px;position: absolute;border-radius: 100%;z-index:99;box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);background: url('../images/iphone.jpg') no-repeat;display: none;}
.small { display: block; }
.magnify_02 {width: 400px; margin: 50px auto; position: relative;}
.large_02 {width: 175px; height: 175px;position: absolute;border-radius: 100%;z-index:99;box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);background: url('../images/iphone.jpg') no-repeat;display: none;}
.small_02 { display: block; }
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
});
}
/




