<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜</title>
<style>
* {
margin: 0;
padding: 0;
}
.preview {
width: 400px;
height: 300px;
position: relative;
border: 1px solid #000;
}
.preview>img {
width: 100%;
height: 100%;
}
.zoomPup {
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
background: rgba(255, 130, 27, 0.411);
}
.zoomDiv {
width: 300px;
height: 300px;
position: absolute;
left: 102%;
top: 0;
overflow: hidden;
border: 1px solid #000;
}
.zoomDiv img {
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="preview">
<img src="./img/img-modified.jpg" alt="">
</div>
<script>
var perview = document.querySelector('.preview')
var zoomPup = null, zoomDiv = null, img = null
perview.onmouseover = function () {
zoomPup = document.querySelector('.zoomPup')
zoomDiv = document.querySelector('.zoomDiv')
img = document.querySelector('#img')
if (!zoomPup) {
zoomPup = `<div class='zoomPup'></div>`
zoomDiv = `<div class='zoomDiv'>
<img id='img' src='${perview.children[0].src}'>
</div>`
perview.innerHTML += zoomPup
perview.innerHTML += zoomDiv
} else {
zoomPup.style.display = 'block'
zoomDiv.style.display = 'block'
}
perview.onmousemove = function (ev) {
move(ev)
}
}
function move(moveEv) {
var offsetX = moveEv.clientX - perview.offsetLeft
var offsetY = moveEv.clientY - perview.offsetTop
var left = offsetX - 50, top = offsetY - 50
if (offsetX - 50 < 0) {//左边
left = 0
}
if (offsetX + 50 > 400) {//右边
left = 300
}
if (offsetY - 50 < 0) {//上边
top = 0
}
if (offsetY + 50 > 300) {//下边
top = 200
}
zoomPup.style.left = left + 'px'
zoomPup.style.top = top + 'px'
img.style.left= -img.clientWidth/perview.clientWidth*zoomPup.offsetLeft+'px'
img.style.top= -img.clientHeight/perview.clientHeight*zoomPup.offsetTop+'px'
}
perview.onmouseout = function () {
perview.onmousemove = null
zoomPup.style.display = 'none'
zoomDiv.style.display = 'none'
}
</script>
</body>
</html>