放大镜功能在实际的网站中非常常见,但是如何用js代码来实现呢,我认为有以下难点
难点:
- 遮蔽层的显示和隐藏
- 遮蔽层所能在X和Y轴移动的最大距离
- 大图的移动距离和方向
鼠标放上之前:
放上之后:
<!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>Document</title>
<style>
.phone {
position: relative;
width: 500px;
height: 500px;
border: 1px solid #ccc;
}
#smallimg {
width: 100%;
height: 100%;
}
.shelter {
display: none;
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background-color: yellow;
opacity: 0.4;
cursor: move;
}
.big {
display: none;
position: absolute;
top: 0;
left: 510px;
width: 800px;
height: 800px;
border: 1px solid #ccc;
overflow: hidden;
}
#bigimg {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="phone">
<img src="./113.jpeg" id="smallimg">
<div class="shelter"></div>
<div class="big"><img src="./113.jpeg" id="bigimg"></div>
</div>
<script>
var phone = document.querySelector('.phone');
var shelter = document.querySelector('.shelter');
var big = document.querySelector('.big');
var bigimg = document.querySelector('#bigimg');
//隐藏或显示放大镜和遮蔽层
phone.addEventListener('mousemove', function () {
shelter.style.display = 'block';
big.style.display = 'block';
})
phone.addEventListener('mouseout', function () {
shelter.style.display = 'none';
big.style.display = 'none';
})
phone.addEventListener('mousemove', function (e) {
var x = e.pageX - phone.offsetLeft;
var y = e.pageY - phone.offsetTop;
var shelterX = x - shelter.offsetWidth / 2;//遮蔽层的移动距离
var shelterY = y - shelter.offsetHeight / 2;//遮蔽层的移动距离
//判断遮蔽层的停止位置 用遮蔽层的最大移动位置
if (shelterX <= 0) {
shelterX = 0;
}
else if (shelterX >= phone.offsetWidth - shelter.offsetWidth) {
shelterX = phone.offsetWidth - shelter.offsetWidth;//phone.offsetWidth - shelter.offsetWidth X轴的移动距离
}
if (shelterY <= 0) {
shelterY = 0;
}
else if (shelterY >= phone.offsetHeight - shelter.offsetHeight) {// phone.offsetHeight - shelter.offsetHeight Y轴的移动距离
shelterY = phone.offsetHeight - shelter.offsetHeight;
}
shelter.style.left = shelterX + 'px';
shelter.style.top = shelterY + 'px';
//大图片移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
var bigMax = bigimg.offsetWidth - big.offsetWidth;//大图的最大移动距离
var bigX = shelterX * bigMax / (phone.offsetWidth - shelter.offsetWidth);
var bigY = shelterY * bigMax / (phone.offsetHeight - shelter.offsetHeight);
bigimg.style.left = -bigX + 'px';
bigimg.style.top = -bigY + 'px';
})
</script>
</body>
</html>