北京乐逍遥网站设计有限公司|乐逍遥网站设计|乐逍遥网站建设|乐逍遥建站|php知识|前端技术|后端技术|网站源码|移动开发|网站运营|UI设计|数据库|网站设计|网站开发|小程序|乐逍遥每日一句|乐逍遥福利图片
主页 > 前端开发 > JavaScript >

JS实现放大镜效果

时间:2020-09-25  编辑:

今天带来JS实现放大镜效果教程详解

JS实现放大镜效果,供大家参考,具体内容如下

鼠标移到图片上就可以放大一块区域

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
  #small{
    width: 700px;
    height: 340px;
    position: absolute;
    left: 70px;
    top: 100px;
  }
  #small img{
    width: 100%;
    height: 100%;
  }
  #mark{
    width: 200px;
    height: 200px;
    background-color:white;
    position: absolute;
    opacity: 0.5;
    filter: alpha(opacity=50);
    left: 0px;
    top: 0px;
    display: none;
  }
  #big{
    width: 400px;
    height: 400px;
    border: 1px solid black;
    left: 800px;
    top: 100px;
    position: absolute;
    overflow: hidden;
    display: none;
  }
  #big img{
    width: 1400px;
    height: 680px;
    position: absolute;
    left: 0px;
    top: 0px;
  }
</style>
<script>
  window.onload = function(){
    var oSmall = document.getElementById("small");
    var oBig = document.getElementById("big");
    var oMark = document.getElementById("mark");
    var oBigImg = oBig.getElementsByTagName("img")[0];
 
    oSmall.onmouseover = function(){
      oMark.style.display = "block";
      oBig.style.display = "block";
    }
    oSmall.onmouseout = function(){
      oMark.style.display = "none";
      oBig.style.display = "none";
    }
    oSmall.onmousemove = function(ev){
      var e = ev || window.event;
      var l = e.clientX - oSmall.offsetLeft - 100;
      if(l <= 0){
        l = 0;
      }
      if(l >= (700-200)){
        l = 500;
      }
      var t = e.clientY - oSmall.offsetTop - 100;
      if(t <= 0){
        t = 0;
      }
      if(t >= (340-200)){
        t = 140;
      }
      oMark.style.left = l + 'px';
      oMark.style.top = t + 'px';
 
      /* 右边图片移动方向与左边图片方向相反且成倍数移动 */
      oBigImg.style.left = l * -2 + 'px';
      oBigImg.style.top = t * -2 + 'px';
 
    }
  }
</script>
 
 
<div id="small">
  <img src="地狱之门卫士 加里奥.jpg" alt="怎么回事" style="width: auto;">
  <div id="mark"></div>
</div>
<div id="big">
  <img src="地狱之门卫士 加里奥.jpg" alt="怎么回事" style="width: 98%;">
</div>

返回
顶部