js实现商城放大镜效果

首页 / 新闻资讯 / 正文

css部分

* {             margin: 0;             padding: 0;         }          /* img {             vertical-align: top;             } */          .box {             width: 350px;             height: 350px;             position: relative;             border: 1px solid black;             margin: 150px 0 0 300px;         }          .big {             width: 450px;             height: 450px;             position: absolute;             border: 1px solid black;             left: 400px;             top: 0;             display: none;             overflow: hidden;         }          .small {             position: relative;         }          .mask {             width: 100px;             height: 100px;             background-color: rgba(255, 255, 0, 0.4);             position: absolute;             left: 0;             top: 0;             cursor: move;             display: none;         }          .big img {             position: absolute;             left: 0;             top: 0;         } 

HTML部分

 <div class="box" id="oBox">         <div class="small" id="oSmall">             <img src="./images/001.jpg" alt="">             <div class="mask" id="oMask"></div>         </div>         <div class="big" id="oBig">             <img src="./images/0001.jpg" alt="">         </div>     </div> 

js部分

//第一步获取节点     let box = document.getElementById('oBox');     let small = box.children[0]; //获取盒子的第一个子节点samll     let big = box.children[1]; //获取盒子的第二个子节点big     let mask = small.children[1]; //获取小盒子里的遮罩     let bigImg = big.children[0]; //获取大盒子里的图片       //鼠标进入small 遮罩(mask)大盒子(big)display:block     small.onmouseover = function() {         mask.style.display = 'block';         big.style.display = 'block';      };      //鼠标离开small 遮罩(mask)大盒子(big)display:none     small.onmouseout = function() {         mask.style.display = 'none';         big.style.display = 'none';     };      let x = 0;     let y = 0;       small.onmousemove = function(even) {         var even = even || window.event;          // 获取鼠标在small里的坐标         let x = even.clientX - this.offsetParent.offsetLeft - mask.offsetWidth / 2;         let y = even.clientY - this.offsetParent.offsetTop - mask.offsetHeight / 2;           // 限制住鼠标的坐标导致遮罩的位置越界         if (x < 0) {             x = 0;         } else if (x > small.offsetWidth - mask.offsetWidth) {             x = small.offsetWidth - mask.offsetWidth;         }          if (y < 0) {             y = 0;         } else if (y > small.offsetHeight - mask.offsetHeight) {             y = small.offsetHeight - mask.offsetHeight;         }         mask.style.left = x + 'px';         mask.style.top = y + 'px';         //注意大图片的方向         bigImg.style.top = -y * big.offsetHeight / small.offsetHeight + 'px';         bigImg.style.left = -x * big.offsetWidth / small.offsetWidth + 'px';     };