<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜</title>
<style>
* {
margin: 0;
padding: 0;
}
.left {
position: relative;
width: 400px;
height: 400px;
}
img {
width: 100%;
height: 100%;
vertical-align: bottom;
}
.right {
position: absolute;
top: 0;
left: calc(100% + 10px);
width: 400px;
height: 400px;
background-color: #abf;
overflow: hidden;
}
.slider {
position: absolute;
top: 0px;
left: 0px;
background-color: rgba(255, 255, 255, .5);
width: 200px;
height: 200px;
cursor: move;
display: none;
}
.big-pic {
position: absolute;
top: 0px;
left: 0px;
width: 800px;
height: 800px;
}
</style>
</head>
<body>
<div class="left">
<div class="slider"></div>
<img src="https://img1.baidu.com/it/u=4251554897,2173491742&fm=253&fmt=auto&app=120&f=JPEG?w=812&h=800" alt="">
<div class="right">
<img class="big-pic" src="https://img1.baidu.com/it/u=4251554897,2173491742&fm=253&fmt=auto&app=120&f=JPEG?w=812&h=800" alt="">
</div>
</div>
<script>
let slider = document.querySelector('.slider')
let left_img = document.querySelector('.left')
let right = document.querySelector('.right')
let big_img = document.querySelector('.big-pic')
left_img.addEventListener('mousemove', e => {
slider.style.display = 'block'
right.style.display = 'block'
const left = Math.max(0, Math.min(parseInt(e.clientX - slider.offsetWidth / 2), left_img.offsetWidth - slider.offsetWidth))
slider.style.left = left + 'px'
const top = Math.max(0, Math.min(parseInt(e.clientY - slider.offsetHeight / 2), left_img.offsetHeight - slider.offsetHeight))
slider.style.top = top + 'px'
big_img.style.left = -left * 2 + 'px'
big_img.style.top = -top * 2 + 'px'
})
left_img.addEventListener('mouseleave', e => {
slider.style.display = 'none'
right.style.display = 'none'
})
</script>
</body>
</html>
