局部放大镜效果
实际上是两张图片 一张小图一张大图
大的图隐藏,当鼠标放在小图上,大的图才会显示,并跟随鼠标局部放大
<!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>
.img {
position: relative;
top: 100px;
left: 100px;
width: 400px;
height: 400px;
border: 1px solid #333;
}
.mask {
display: none;
position: absolute;
top: 0px;
left: 0px;
width: 300px;
height: 300px;
background-color: #FEDE4F;
opacity: .5;
/* 透明度 */
cursor: move;
}
.img-big {
display: none;
position: absolute;
left: 410px;
top: 0;
width: 500px;
height: 500px;
overflow: hidden;
border: 1px solid #333;
z-index: 999;
}
.img-big .big {
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<div class="img">
<img src="../imgs/s3.png">
<div class="mask"></div>
<div class="img-big">
<img src="../imgs/b3.jpg" class="big">
</div>
</div>
<script>
var img = document.querySelector('.img');
var mask = document.querySelector('.mask');
var bigbox = document.querySelector('.img-big');
var big = document.querySelector('.big');
img.addEventListener('mouseover', function() {
mask.style.display = 'block';
bigbox.style.display = 'block';
})
img.addEventListener('mouseout', function() {
mask.style.display = 'none';
bigbox.style.display = 'none';
})
img.addEventListener('mousemove', function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var maskX = x - mask.offsetHeight / 2;
var maskY = y - mask.offsetHeight / 2;
var maskMax = img.offsetWidth - mask.offsetWidth
if (maskX <= 0) {
maskX = 0;
} else if (maskX >= maskMax) {
maskX = maskMax
}
if (maskY <= 0) {
maskY = 0;
} else if (maskY >= maskMax) {
maskY = maskMax
}
mask.style.top = maskY + 'px';
mask.style.left = maskX + 'px';
big.style.top = -maskY * big.offsetWidth / img.offsetWidth + 'px';
big.style.left = -maskX * big.offsetWidth / img.offsetWidth + 'px';
})
</script>
</body>
</html>