<head lang="en"> <meta charset="UTF-8"> <title>哈哈</title> <style> * { margin: 0; padding: 0; } .box { width: 350px; height: 350px; margin: 100px; border: 1px solid #ccc; position: relative; } .big { width: 400px; height: 400px; position: absolute; top: 0; left: 360px; border: 1px solid #ccc; overflow: hidden; display: none; } .mask { width: 200px; height: 200px; background: rgba(255, 255, 0, 0.4); position: absolute; top: 0px; left: 0px; cursor: move; display: none; } .small { position: relative; } </style> </head>
<body> <div class="box" id="box"> <div class="small"> <!--小层--> <img src="images/small.png" width="350" alt="" /> <div class="mask"></div> <!--遮挡层--> </div> <!--小图--> <div class="big"> <!--大层--> <img src="images/big.jpg" width="800" alt="" /> <!--大图--> </div> <!--大图--> </div>
<script> var box = document.getElementById('box'); var small = box.children[0]; //小图盒子 var mask = small.children[1]; //遮挡层 var big = box.children[1]; //大图盒子 var bigImage = big.children[0]; //大图
//鼠标进入小层 让遮挡层和大图的div显示出来 box.onmouseover = function() { mask.style.display = 'block'; big.style.display = 'block'; } //鼠标进出小层 box.onmouseout = function() { mask.style.display = 'none'; big.style.display = 'none'; }
//鼠标在小层移动 small.onmousemove = function(e) { var x = e.clientX - (mask.offsetWidth / 2) - 100; var y = e.clientY - (mask.offsetHeight / 2) - 100; //x最大取值范围(小层宽-遮挡层宽) 最小值 x = x > (small.offsetWidth - mask.offsetWidth) ? small.offsetWidth - mask.offsetWidth : x; //最大取值范围 y = y > (small.offsetHeight - mask.offsetHeight) ? small.offsetHeight - mask.offsetHeight : y; //最大取值范围 x = x < 0 ? 0 : x; //最小取值范围 y = y < 0 ? 0 : y; //最小取值范围 mask.style.left = x + 'px'; mask.style.top = y + 'px';
//大图的移动距离? //遮挡层的移动距离/大图的移动距离=遮挡层最大移动距离/大图最大移动距离 //大图的移动距离 = 遮挡层的移动距离*大图最大移动距离/遮挡层的遮挡距离
//遮挡层的最大移动距离 var maskX = small.offsetWidth - mask.offsetWidth; var maskY = small.offsetHeight - mask.offsetHeight;
var maxX = bigImage.offsetWidth - big.offsetWidth; var maxY = bigImage.offsetHeight - big.offsetHeight;
var bigImageX = x * maxX / maskX; var bigImageY = y * maxY / maskY;
bigImage.style.marginLeft = -bigImageX + 'px'; bigImage.style.marginTop = -bigImageY + 'px';
} </script>
</body>
</html>