<!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;
}
.box {
position: relative;
margin: 100px 0;
width: 450px;
height: 450px;
border: 1px solid #ccc;
}
.box .img {
width: 100%;
height: 100%;
}
.box .mask {
display: none;
position: absolute;
width: 300px;
height: 300px;
left: 0;
top: 0;
background-color: rgb(231, 175, 20);
opacity: .5;
cursor: move;
}
.box .luper {
display: none;
position: absolute;
top: -1px;
left: 450px;
width: 535px;
height: 535px;
z-index: 999;
border: 1px solid #ccc;
overflow: hidden;
}
.box .big {
position: absolute;
left: 0;
top: 0;
}
</style>
<script>
window.addEventListener('load', function() {
var box = document.querySelector('.box');
var mask = document.getElementById('mask');
var luper = document.querySelector('.luper');
var big = document.querySelector('.big');
// 当鼠标移进去时将隐藏的遮罩层显示出来
box.addEventListener('mouseover', function(e) {
this.style.crusor = 'move';
mask.style.display = 'block';
luper.style.display = 'block';
// 当鼠标移动时将移动的位置赋予遮罩层
});
// 当我鼠标离开时就给我隐藏
box.addEventListener('mouseout', function() {
mask.style.display = 'none';
luper.style.display = 'none';
});
// 当鼠标移动时赋予遮罩层的位置
box.addEventListener('mousemove', function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
maskX = x - mask.offsetWidth / 2;
maskY = y - mask.offsetWidth / 2;
// 左右移动最低为0最高为大盒子的宽度减去小盒子的宽度
maskMaxWidth = box.offsetWidth - mask.offsetWidth;
maskMaxHeight = box.offsetHeight - mask.offsetHeight;
maskY = maskY < 0 ? 0 : maskY;
maskX = maskX < 0 ? 0 : maskX;
maskX = maskX > maskMaxWidth ? maskMaxWidth : maskX;
maskY = maskY > maskMaxHeight ? maskMaxHeight : maskY
mask.style.left = maskX + 'px';
mask.style.top = maskY + 'px';
// 打个鼠标移动时,右边的移动距离按比例放大
// /大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层的最大移动距离
bigMax = big.offsetWidth - luper.offsetWidth;
bigMaxY = big.offsetHeight - luper.offsetHeight;
bigX = maskX * bigMax / maskMaxWidth;
bigY = maskY * bigMaxY / maskMaxHeight;
big.style.left = -bigX + 'px';
big.style.top = -bigY + 'px';
});
});
</script>
<div class="box">
<img src="images/cy2.jpg" alt="" class="img">
<div class="mask" id="mask"></div>
<div class="luper"><img src="images/cy2.jpg" alt="" class="big"></div>
</div>
</head>
<body>
</body>
</html>