jQuery仿淘宝之放大镜效果

翅膀的初衷

发表于2013-10-09 21:57:23

  原理:两张图片,一张小图,一张大图,先获取鼠标在小图上面的坐标,然后以一个div来显示大图,并根据小图的坐标乘以大图除以小图得到的倍数定位!放大倍数为小图与大图之间的比例,如小图是100*100,大图是1000*1000,则放大倍数1000/100 为10位!

  请将以下代码存为jquery.JNMagnifier.js,注:本代码必须与JQuery一起使用!

  原创内容,转载请注明作者:翅膀的初衷 出自:http://www.jiniannet.com

/* * * JQUERY 之简易放大镜插件 * Author:翅膀的初衷 * Date:2011-11-16 * 网址:www.jiniannet.com * 请保留本信息 */ (function($){ $.fn.JNMagnifier=function(setting){ if(setting&&setting.renderTo){ if(typeof(setting.renderTo)=="string"){ setting.renderTo = $(setting.renderTo); } }else{ return; } var _img_org_ = this.children("img"); _img_org_.css("cursor","pointer"); var __w = 0; var __h = 0; var __left = this.offset().left; var __top = this.offset().top; if(this.offsetParent()) { __left+=this.offsetParent().offset().left; __top+=this.offsetParent().offset().top; } var _move_x = 0; var _move_y = 0; var _val_w = (setting.renderTo.width() / 2); var _val_h = (setting.renderTo.height() / 2); _img_org_.mouseover(function(){ setting.renderTo.html('<img src="' + _img_org_.attr("src") + '" style="position:absolute;" id="JNMagnifierrenderToImg" />'); setting.renderTo.show(); var timer = setInterval(function(){ __w = $("#JNMagnifierrenderToImg").width() / _img_org_.width(); __h = $("#JNMagnifierrenderToImg").height() /_img_org_.height(); if(__w>0){ clearInterval(timer); } },100); }); _img_org_.mouseout(function(){ setting.renderTo.hide(); }); _img_org_.mousemove(function(e){ _move_x =0-Math.round((document.documentElement.scrollLeft+e.clientX-__left) * __w - _val_w); _move_y =0-Math.round((document.documentElement.scrollTop+e.clientY-__top) * __h - _val_h); $("#JNMagnifierrenderToImg").css({"left":_move_x + "px ","top":_move_y + "px"}); }); } })(jQuery);

调用方法:

$("#ShowPictureBox").JNMagnifier({ renderTo:"#ShowBigPictureBox" });

 

html:

 

演示效果: