放大镜
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/cec00b850a4749ddb917fca108dbb18f.png)
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品放大镜</title>
<link rel="stylesheet" href="css/reset.css">
<style>
.product-intro {
position: relative;
width: 450px;
margin: 100px 0 0 200px;
border: 1px solid #ccc;
}
.preview {
position: relative;
}
.enlargement {
display: none;
overflow: hidden;
position: absolute;
top: -1px;
left: 450px;
width: 540px;
height: 540px;
border: 1px solid #ccc;
}
.mask {
display: none;
position: absolute;
top: 0;
left: 0;
width: 60%;
height: 60%;
background-color: rgba(228, 228, 11, 0.3);
border: 1px solid rgba(122, 122, 122, .4);
cursor: move;
}
.active {
display: block;
}
</style>
</head>
<body>
<div class="product-intro">
<div class="preview">
<img src="images/m30.jpg" width="450" height="450" alt="m30">
<div class="mask"></div>
</div>
<div class="enlargement">
<img src="images/m30-big.jpg" alt="m30">
</div>
</div>
<script src="js/common.js"></script>
<script>
var oPreview = $('.preview');
var oMask = $('.mask');
var oEnlarge = $('.enlargement');
var oEnlargeImg = $('.enlargement>img');
var mouseEventMap = {
mouseenter: function (e) {
oMask.classList.add('active');
oEnlarge.classList.add('active');
},
mouseleave: function (e) {
oMask.classList.remove('active');
oEnlarge.classList.remove('active');
},
mousemove: function (e) {
var x = e.clientX - oMask.offsetWidth / 2 - getPosition(oPreview).left;
var y = e.clientY - oMask.offsetHeight / 2 - getPosition(oPreview).top;
x = Math.min(x, oPreview.offsetWidth - oMask.offsetWidth);
x = Math.max(x, 0);
y = Math.min(y, oPreview.offsetHeight - oMask.offsetHeight);
y = Math.max(y, 0);
oMask.style.left = x + 'px';
oMask.style.top = y + 'px';
var moveX = (oEnlargeImg.offsetWidth - oEnlarge.offsetWidth) / (oPreview.offsetWidth - oMask.offsetWidth);
var moveY = (oEnlargeImg.offsetHeight - oEnlarge.offsetHeight) / (oPreview.offsetHeight - oMask.offsetHeight);
oEnlargeImg.style.marginLeft = -x * moveX + 'px';
oEnlargeImg.style.marginTop = -y * moveX + 'px';
}
}
oPreview.addEventListener('mouseenter', handle, false);
oPreview.addEventListener('mouseleave', handle, false);
oPreview.addEventListener('mousemove', handle, false);
function handle(e) {
if (mouseEventMap[e.type] && typeof mouseEventMap[e.type] === 'function') {
mouseEventMap[e.type](e);
}
}
</script>
</body>
</html>