JavaScript基础学习 放大镜
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=devcie-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.mask {
display: none;
position: absolute;
top: 0;
left: 0;
width: 400px;
height: 400px;
background-color: pink;
opacity: .5;
cursor: move;
}
.father {
position: relative;
height: 500px;
width: 500px;
margin-left: 100px;
margin-top: 50px;
}
.big {
display: none;
position: absolute;
width: 400px;
height: 400px;
left: 700px;
top: 0;
background-color: yellow;
}
.big img {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div>
<div class="father">
<img src="image/b3.png">
<div class="mask"></div>
<div class="big">
<img src="image/big.jpg" class="bigImg">
</div>
</div>
</div>
<script>
var father = document.querySelector('.father');
var mask = document.querySelector('.mask');
var big = document.querySelector('.big');
var bigImg = document.querySelector('.bigImg');
// 鼠标经过大盒子时,显示遮挡层和大图片
father.addEventListener('mouseover', function() {
mask.style.display = 'block';
big.style.display = 'block';
})
// 鼠标移开大盒子时,把遮挡层和大图片进行遮挡
father.addEventListener('mouseout', function() {
mask.style.display = 'none';
big.style.display = 'none';
})
// 鼠标移动让我们的遮挡层跟着鼠标一起移动
father.addEventListener('mousemove', function(e) {
var x = e.pageX - father.offsetLeft;
var y = e.pageY - father.offsetTop;
var maskX = x - 200;
var maskY = y - 200;
// 让遮挡层不要超出我们的大盒子,如果超出就让遮挡层处于边界
if (maskX < 0) {
maskX = 0;
} else if (maskX >= 300) {
maskX = 300;
}
if (maskY < 0) {
maskY = 0;
} else if (maskY >= 300) {
maskY = 300;
}
mask.style.left = maskX + 'px';
mask.style.top = maskY + 'px';
var bigMax = bigImg.offsetWidth - big.offsetWidth;
var bigX = maskX * bigMax / 1000;
var bigY = maskY * bigMax / 1000;
bigImg.style.left = -bigX + 'px';
bigImg.style.top = -bigY + 'px';
})
</script>
</body>
</html>