js图片放大镜特效代码

 1 <script language="JavaScript">

 2 <!--

 3 var srcX = 1024; //原图长宽

 4 var srcY = 768;

 5 var bigX = 500; //原比例预览大小,可以设置成任意大小

 6 var bigY = 300;

 7 var smallX = 256; //缩略图大小,要与原大小成比例

 8 var smallY = 192;

 9 var viewX = bigX / srcX * smallX; //预览范围

10 var viewY = bigY / srcY * smallY;

11 var bl = srcX / smallX;//缩小比例

12 var border = 8; //边框

13 window.onload=function (){

14     bigbox.style.borderWidth=border;

15     bigbox.style.width=bigX+border*2;

16     bigbox.style.height=bigY+border*2;

17     smallpic.width=smallX;

18     smallpic.height=smallY;

19     view.style.width=viewX;

20     view.style.height=viewY;

21     smallbox.style.borderWidth=border;

22     if (window.event){

23         smallbox.style.width=smallpic.offsetWidth+border*2;

24         smallbox.style.height=smallpic.offsetHeight+border*2;

25     }else{

26         smallbox.style.width=smallpic.offsetWidth;

27         smallbox.style.height=smallpic.offsetHeight;

28     }

29     move(event);

30 }

31 function move(e){

32     var e = window.event?window.event:e;

33     var iebug = 0;

34     if (window.event){

35         var vX = e.offsetX - viewX/2;

36         var vY = e.offsetY - viewY/2;

37     }else{

38         var vX = e.pageX - viewX/2 - smallbox.offsetLeft - border;

39         var vY = e.pageY - viewY/2 - smallbox.offsetTop - border;

40         iebug = 2;

41     }

42     if (vX < 0) vX = 0;

43     if (vY < 0) vY = 0;

44     if (vX > smallX - viewX - iebug) vX = smallX - viewX - iebug;

45     if (vY > smallY - viewY - iebug) vY = smallY - viewY - iebug;

46     view.style.left = vX + smallbox.offsetLeft + border;

47     view.style.top = vY + smallbox.offsetTop + border;

48     bigbox.style.backgroundPosition= - vX * bl + " " + -vY * bl;

49 }

50 //-->

51 </script>

52 

53 <style type="text/css">

54 <!--

55 *{padding:0;margin:0}

56 img{display:block;}

57 #smallbox{border:1px #c33 solid;float:left;width:0;height:0;overflow:hidden}

58 #bigbox{border:1px #c33 solid;width:0px;height:0px;float:left;background:url('/upload/20071130224657571.jpg') no-repeat;}

59 #view{border:1px #ddd solid;width:0px;height:0px;position:absolute}

60 .head{text-align:center;line-height:40px;font:bold 16px/40px;color:red}

61 //-->

62 </style>

63 <div class="head">图片放大效果</div>

64 <div id="smallbox"><img id="smallpic" src="/upload/20071130224657571.jpg" border="0" onmousemove="move(event)"></div>

65 <div id="bigbox"></div>

66 <div id="view"></div>

代码最终的效果如下图:

js图片放大镜特效代码

你可能感兴趣的:(js)