<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片缩放</title> <style type="text/css"> *{ margin: 0; padding: 0; } #minBox{ border:1px solid #ccc; width: 350px; height: 350px; position: relative; top: 50px; left: 50px; } #minBox img{ position: absolute; } #smBox{ display: none; position: absolute; width:150px; height: 150px; background-color: yellow; opacity: 0.3; } #maxBox { display: none; position: absolute; overflow: hidden; left:500px; top:50px; width:500px; height: 500px; border:1px solid #d9d9d9; } #maxBox img { position: absolute; } </style> </head> <body> <div id="minBox"> <img src="img/min.jpg"> <div id="smBox"></div> </div> <div id="maxBox"> <img src="img/max.jpg"> </div> <script type="text/javascript"> //获取节点 var minBox =document.getElementById("minBox"); var smBox = document.getElementById("smBox"); var maxBox = document.getElementById("maxBox"); var maxImg = maxBox.children[0]; //小块鼠标移动事件事件 minBox.onmousemove = function(){ var e = e || window.event; smBox.style.display = "block"; maxBox.style.display = "block"; //计算小块的位置 //定义 var sLeft = e.clientX - smBox.offsetWidth/2 -minBox.getBoundingClientRect().left; var sTop = e.clientY - smBox.offsetWidth/2 - minBox.getBoundingClientRect().top; //判断左右边界,小块距离左边的距离小于0,则意味超界,设置它的left为0; //右边边界判断,小块的最大宽度不能>(minBox的视口宽度- 小块本身宽度), if(sLeft<0){ sLeft= 0; }else if(sLeft >minBox.clientWidth- smBox.offsetWidth){ sLeft = minBox.clientWidth - smBox.offsetWidth; } //上下边界同理 if(sTop<0){ sTop = 0; }else if(sTop > minBox.clientHeight - smBox.offsetHeight){ sTop = minBox.clientHeight - smBox.offsetHeight; } //鼠标移动、小块跟着移动 smBox.style.left = sLeft + "px"; smBox.style.top = sTop + "px" ; //计算小块在minBox移动的比例,大图同比例在maxBox移动; //定义设置moveX、moveY 暂存比例 var moveX = sLeft/(minBox.clientWidth - smBox.offsetWidth); var moveY = sTop/(minBox.clientHeight - smBox.offsetHeight); console.log(moveY); //大图maxImg移动 maxImg.style.left = - moveX*(maxImg.clientWidth - maxBox.offsetWidth) +"px"; maxImg.style.top = - moveY* (maxImg.clientHeight - maxBox.offsetHeight) +"px"; } //移出滑块的时候 minBox.onmouseleave = function() { smBox.style.display = "none"; maxBox.style.display = "none"; } </script> </body> </html>