【IT168技术文档】
客户有个需求,就是要在产品展示的时候,需要会图片放大预览的效果,OK,很简单~大家完全可以把下面的Copy过去,用到项目中去!
最主要的是下面这个JS文件,我加了点注释:
JS:
(function($){ $.fn.jqueryzoom = function(options){ //设置预览的边框属性 var settings = { xzoom: 200, //宽 yzoom: 200, //高 offset: 10, //与原图的距离 position: "right" //预览显示的停靠位置,可以改为左边(left)等其他地方 }; //这里相当与初始化设置给传入的对象 if(options) { $.extend(settings, options); } //鼠标悬停的效果 $(this).hover(function(){ //设置大小 var imageLeft = $(this).get(0).offsetLeft; var imageRight = $(this).get(0).offsetRight; var imageTop = $(this).get(0).offsetTop; var imageWidth = $(this).get(0).offsetWidth; var imageHeight = $(this).get(0).offsetHeight; //添加alt属性 var bigimage = $(this).attr("alt"); //判断div.zoomdiv是否存在,如果不存在,就在传入对象的后面插入 if($("div.zoomdiv").get().length == 0){ $(this).after("<div class='zoomdiv'><img class='bigimg' src='"+bigimage+"'/></div>"); } //判断停靠位置 if(settings.position == "right"){ leftpos = imageLeft + imageWidth + settings.offset; //自己想下问什么,很清楚了 }else{ leftpos = imageLeft - settings.xzoom - settings.offset; } //添加样式表和设置高 宽 $("div.zoomdiv").css({ top: imageTop,left: leftpos }); $("div.zoomdiv").width(settings.xzoom); $("div.zoomdiv").height(settings.yzoom); $("div.zoomdiv").show(); //鼠标移除效果 $(document.body).mousemove(function(e){ //预览图片的class的宽和高 var bigwidth = $(".bigimg").get(0).offsetWidth; var bigheight = $(".bigimg").get(0).offsetHeight; var scaley ='x'; var scalex= 'y'; if(isNaN(scalex)|isNaN(scaley)){ var scalex = Math.round(bigwidth/imageWidth) ; var scaley = Math.round(bigheight/imageHeight); } mouse = new MouseEvent(e); //这里调用函数 scrolly = mouse.y - imageTop - ($("div.zoomdiv").height()*1/scaley)/2 ; $("div.zoomdiv").get(0).scrollTop = scrolly * scaley ; scrollx = mouse.x - imageLeft - ($("div.zoomdiv").width()*1/scalex)/2 ; $("div.zoomdiv").get(0).scrollLeft = (scrollx) * scalex ; }); },function(){ $("div.zoomdiv").hide(); $(document.body).unbind("mousemove"); $(".lenszoom").remove(); $("div.zoomdiv").remove(); }); } })(jQuery); //单例 //设置传入对象的x,y是鼠标相应与左上角的位置 function MouseEvent(e) { this.x = e.pageX this.y = e.pageY }