$(function(){ $.fn.magnifying = function(){ var that = $(this), $imgcon = that.find('.con-fangdaimg'),//正常图片容器 $img = $imgcon.find('img'),//正常图片,还有放大图片集合 $drag = that.find('.magnifyingbegin'),//拖动滑动容器 $show = that.find('.magnifyingshow'),//放大镜显示区域 $showimg = $show.find('img'),//放大镜图片 $imglist = that.find('.con-fangda-imglist > li >img'), multiple = $show.width()/$drag.width(); $imgcon.mousemove(function(e){ $drag.css('display','block'); $show.css('display','block'); //获取坐标的两种方法 // var ix = e.clientx - this.offsetleft - $drag.width()/2, // iy = e.clienty - this.offsettop - $drag.height()/2, var ix = e.pagex - $(this).offset().left - $drag.width()/2, iy = e.pagey - $(this).offset().top - $drag.height()/2, maxx = $imgcon.width()-$drag.width(), maxy = $imgcon.height()-$drag.height(); /*这一部分可代替下面部分,判断最大最小值 var dx = ix < maxx ? ix > 0 ? ix : 0 : maxx, dy = iy < maxy ? iy > 0 ? iy : 0 : maxy; $drag.css({left:dx+'px',top:dy+'px'}); $showimg.css({marginleft:-3*dx+'px',margintop:-3*dy+'px'});*/ ix = ix > 0 ? ix : 0; ix = ix < maxx ? ix : maxx; iy = iy > 0 ? iy : 0; iy = iy < maxy ? iy : maxy; $drag.css({left:ix+'px',top:iy+'px'}); $showimg.css({marginleft:-multiple*ix+'px',margintop:-multiple*iy+'px'}); //return false; }); $imgcon.mouseout(function(){ $drag.css('display','none'); $show.css('display','none'); }); $imglist.click(function(){ var nowsrc = $(this).data('bigimg'); $img.attr('src',nowsrc); $(this).parent().addclass('active').siblings().removeclass('active'); }); } $("#fangdajing").magnifying(); });