代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.box{width: 500px;height: 300px;border: 1px solid;position: relative;img{width: 500px;height: 300px;}.active{width: 100px;height: 100px;background: rgba(255, 255, 0, 0.329);position: absolute;left: 0;top: 0;display: none;}}.box2{display: none;width: 500px;height: 300px;border: 1px solid;position: relative;overflow: hidden;top: -300px;left: 600px;img{width: 1000px;height: 600px;position: absolute;left: 0;top: 0;}}</style>
</head>
<body><div class="box"><img src="https://n.sinaimg.cn/sinakd2020417s/329/w1200h729/20200417/a418-iskepxs9886958.jpg" alt=""><div class="active"></div></div><div class="box2"><img src="https://n.sinaimg.cn/sinakd2020417s/329/w1200h729/20200417/a418-iskepxs9886958.jpg" alt=""></div><script>let box = document.querySelector('.box')let active = document.querySelector('.active')let box2 = document.querySelector('.box2')let img = document.querySelector('.box2 img')// 鼠标移入事件box.addEventListener('mouseover',function(){// 让黄色区域显示出来active.style.display='block'box2.style.display='block' })// 鼠标移出事件box.addEventListener('mouseout',function(){// 让黄色区域隐藏active.style.display='none'box2.style.display='none' })// 鼠标移动box.addEventListener('mousemove',function(e){// 设置鼠标移动时处于active的中心let x = e.clientX-active.offsetWidth/2let y = e.clientY-active.offsetHeight/2// 设定盒子移动的范围x<=0?x=0:''y<=0?y=0:''// 最大x轴等于大盒子减小盒子的宽度let maxX = box.offsetWidth-active.offsetWidthlet maxY = box.offsetHeight-active.offsetHeightx>maxX?x=maxX:''y>maxY?y=maxY:''active.style.left = x+'px'active.style.top = y+'px' //大图最大移动距离var imgWidth = img.offsetWidth - box.offsetWidth;var imgHeight = img.offsetHeight - box.offsetHeight;//大图片的移动距离 = mask移动距离 * 大图最大移动距离 /mask的最大移动距离 var bigX = x * imgWidth / maxX;var bigY = y * imgHeight / maxY;// 修图图片位置img.style.left = (-bigX) + 'px';img.style.top = (-bigY) + 'px';})</script>
</body>
</html>
效果图: