引语:jQuery提供了很多插件,我们在开发的过程使用插件能节省时间简化开发也避免从头开始编写每个组件,单我们除了懂得使用别人已编写好的插件以外,也到懂得如何封装属于我们自己的插件,以下就是封装jQuery插件的步骤,以放大镜效果为例。
附效果文件:下载
1、导入素材,已经封装成jQ版的放大镜
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>无标题文档</title> 6 <style> 7 *{ margin:0; padding:0;} 8 9 #min{ height:350px; width:350px; border:1px solid #ccc; position:relative; top:20px; left:20px; cursor:move;} 10 #kuai{ height:175px; width:175px; background:#FC3; position:absolute; left:0; top:0; opacity:0.5; display:none;} 11 12 #max{ width:400px; height:400px; border:1px solid #ccc; position:absolute; left:400px; top:20px; overflow:hidden; display:none} 13 #max img{ position:absolute;} 14 </style> 15 <script src="jquery1.9.1.js"></script> 16 <script> 17 $(function (){ 18 19 $("#min").hover(function (){ 20 21 $("#kuai").show(); 22 $("#max").show(); 23 24 },function (){ 25 $("#kuai").hide(); 26 $("#max").hide(); 27 }); 28 $("#min").mousemove(function (event){ 29 30 var disX=event.pageX-$("#min").offset().left-$("#kuai").width()/2; 31 var disY=event.pageY-$("#min").offset().top-$("#kuai").height()/2; 32 33 var maxWidth=$("#min").width()-$("#kuai").width(); 34 35 var maxHeight=$("#min").height()-$("#kuai").height(); 36 if (disX<=0){ 37 disX=0; 38 } 39 else if (disX>maxWidth){ 40 disX=maxWidth; 41 } 42 if (disY<=0){ 43 disY=0; 44 } 45 else if(disY>maxHeight){ 46 47 disY=maxHeight; 48 } 49 50 $("#kuai").css({ 51 left:disX, 52 top:disY 53 }); 54 var scaleL=disX/maxWidth; 55 var scaleT=disY/maxHeight; 56 $("#max img").css({ 57 left:-scaleL*($("#max img").width()-$("#max").width()), 58 top:-scaleT*($("#max img").height()-$("#max").height()) 59 }); 60 }); 61 }); 62 </script> 63 </head> 64 <body> 65 <div id="min"> 66 <img src="min.jpg"/> 67 <div id="kuai"></div> 68 </div> 69 <div id="max"> 70 <img src="max.jpg"/> 71 </div> 72 </body> 73 </html>