效果图
html
<div class="wrap"> <!-- 小图与遮罩 --> <div id="small"> <img src="../styles/01.jpg" alt=""> <div id="mark"></div> </div> <!-- 等比例放大的大图 --> <div id="big"> <img src="../styles/01.jpg" alt="" id="bigimg"> </div> </div>
css
* { margin: 0; padding: 0; } .wrap { width: 1500px; margin: 10px auto; } #small { width: 500px; height: 768px; float: left; position: relative; } #small img { width: 100%; height: 100%; } #big { /* background-color: seagreen; */ width: 768px; height: 90vh; float: left; /* 超出取景框的部分隐藏 */ overflow: hidden; margin-left: 20px; position: relative; display: none; } #bigimg { /* width: 864px; */ position: absolute; left: 0; top: 0; } #mark { width: 250px; height: 250px; background-color: #fff; opacity: .5; position: absolute; left: 0; top: 0; /* 鼠标箭头样式 */ cursor: move; display: none; }
js
// 获取小图和遮罩、大图、大盒子 var small = document.getElementById("small") var mark = document.getElementById("mark") var big = document.getElementById("big") var bigimg = document.getElementById("bigimg") // 在小图区域内获取鼠标移动事件;遮罩跟随鼠标移动 small.onmousemove = function (e) { // 得到遮罩相对于小图的偏移量(鼠标所在坐标-小图相对于body的偏移-遮罩本身宽度或高度的一半) var s_left = e.pageX - mark.offsetWidth / 2 - small.offsetLeft var s_top = e.pageY - mark.offsetHeight / 2 - small.offsetTop // 遮罩仅可以在小图内移动,所以需要计算遮罩偏移量的临界值(相对于小图的值) var max_left = small.offsetWidth - mark.offsetWidth; var max_top = small.offsetHeight - mark.offsetHeight; // 遮罩移动右侧大图也跟随移动(遮罩每移动1px,图片需要向相反对的方向移动n倍的距离) var n = big.offsetWidth / mark.offsetWidth // 遮罩跟随鼠标移动前判断:遮罩相对于小图的偏移量不能超出范围,超出范围要重新赋值(临界值在上边已经计算完成:max_left和max_top) // 判断水平边界 if (s_left < 0) { s_left = 0 } else if (s_left > max_left) { s_left = max_left } //判断垂直边界 if (s_top < 0) { s_top = 0 } else if (s_top > max_top) { s_top = max_top } // 给遮罩left和top赋值(动态的?因为e.pageX和e.pageY为变化的量),动起来! mark.style.left = s_left + "px"; mark.style.top = s_top + "px"; // 计算大图移动的距离 var levelx = -n * s_left; var verticaly = -n * s_top; // 让图片动起来 bigimg.style.left = levelx + "px"; bigimg.style.top = verticaly + "px"; } // 鼠标移入小图内才会显示遮罩和跟随移动样式,移出小图后消失 small.onmouseenter = function () { mark.style.display = "block" big.style.display = "block" } small.onmouseleave = function () { mark.style.display = "none" big.style.display = "none" }