记录一波
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#view {
width: 490px;
/* height: 300px; */
position: relative;
border: 1px solid red;
margin: 300px auto;
}
#small {
width: 490px;
}
#viewBro {
position: absolute;
width: 100px;
height: 100px;
border: 1px solid red;
overflow: hidden;
}
#viewBro img {
width: 980px;
position: absolute;
}
</style>
</head>
<body>
<div id="view">
<img src="hua.jpg" alt="" id="small">
<div id="viewBro">
<img src="hua.jpg" alt="">
</div>
</div>
</body>
<script>
view.onmousemove = function (e) {
// 获取页面滚动高度
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 获取文档到顶部和左侧的偏移量
var t = this.offsetTop;
var left = this.offsetLeft;
//鼠标偏移量
var x = e.clientX - left;
var y = e.clientY + scrollTop - t;
if (x < 100 / 2 / 2) {
x = 25;
}
if (x > 490 - 100 / 2 / 2) {
x = 490 - 100 / 2 / 2
}
if (y < 100 / 2 / 2) {
y = 25;
}
if (y > 270 - 25) {
y = 270 - 25;
}
//放大镜
viewBro.children[0].style.left = -x * 2 + 50 + 'px';
viewBro.children[0].style.top = -y * 2 + 50 + 'px';
}
</script>
</html>