效果
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>放大镜效果</title>
6 <style type="text/css">
7 #div1 {
8 width: 180px;
9 height: 180px;
10 position: relative;
11 }
12 #div1 img{
13 display: block;
14 }
15 #div2{
16 width: 80px;
17 height: 80px;
18 background: yellow;
19 opacity: 0.5;
20 filter:alpha(opacity=50);
21 position: absolute;
22 left: 0;
23 top:0;
24 display: none;
25 }
26 #div3{
27 display: none;
28 width: 300px;
29 height: 300px;
30 border: 1px solid black;
31 position: absolute;
32 left: 200px;
33 top:0px;
34 overflow: hidden;
35 }
36 #div3 img{
37 display: block;
38 position: absolute;
39 left: 0px;
40 top:0px;
41 }
42 </style>
43 <script type="text/javascript">
44 window.onload=function(){
45 var oDiv1 = document.getElementById("div1");
46 var oDiv2 = document.getElementById("div2");
47 var oDiv3 = document.getElementById("div3");
48 var oImg2 = document.getElementById("img2");
49 oDiv1.onmouseover=function(){
50 oDiv2.style.display = "block";
51 oDiv3.style.display = "block";
52 oDiv1.onmousemove=function(ev){
53 var ev = ev || event;
54 var l = ev.clientX - oDiv2.offsetWidth/2;
55 var t = ev.clientY - oDiv2.offsetHeight/2;
56 if(l<0){
57 l = 0;
58 }
59 if(l>oDiv1.offsetWidth-oDiv2.offsetWidth){
60 l = oDiv1.offsetWidth-oDiv2.offsetWidth;
61 }
62 if(t<0){
63 t = 0;
64 }
65 if(t>oDiv1.offsetHeight-oDiv2.offsetHeight){
66 t = oDiv1.offsetHeight-oDiv2.offsetHeight;
67 }
68 //计算大图的位置
69 var scaleX = l/(oDiv1.offsetWidth-oDiv2.offsetWidth);
70 oImg2.style.left = (oDiv3.offsetWidth-oImg2.offsetWidth)*scaleX+"px";
71 var scaleY = t/(oDiv1.offsetHeight-oDiv2.offsetHeight);
72 oImg2.style.top = (oDiv3.offsetHeight-oImg2.offsetHeight)*scaleY+"px";
73 document.title = scaleX;
74 oDiv2.style.left = l +"px";
75 oDiv2.style.top = t +"px";
76 }
77 }
78 oDiv1.onmouseout=function(){
79 oDiv2.style.display = "none";
80 oDiv3.style.display = "none";
81 }
82 }
83
84 </script>
85 </head>
86 <body>
87 <div id="div1">
88 <img class="img" src="img/b2.jpg"/>
89 <div id="div2"></div>
90 </div>
91 <div id="div3">
92 <img id="img2" src="img/b1.jpg" alt="1" />
93 </div>
94 </body>
95 </html>