index.html
<!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>图片放大镜</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div class="img-wrap">
<div class="mag-wrap">
<img src="img/1.jpg" class="mag-img" alt="">
</div>
<a href="javascript:;" class="img-lk">
<img src="img/1.jpg" class="static-img" alt="">
</a>
</div>
<script src="js/utils.js"></script>
<script src="js/index.js"></script>
</body>
</html>
index.css
.img-wrap {
position: relative;
width: 375px;
height: 522px;
margin: 100px auto;
border: 1px solid #ddd;
box-shadow: 0 0 5px #999;
/* overflow: hidden; */
}
.img-wrap .mag-wrap {
display: none;
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
background-color: #fff;
box-shadow: 0 0 3px #ccc;
overflow: hidden;
}
.img-wrap .mag-wrap.show {
display: block;
transform: scale(1.5);
}
.img-wrap .mag-wrap .mag-img {
position: absolute;
top: 0;
left: 0;
widows: 375px;
height: 500px;
}
.img-wrap .static-img {
width: 100%;
}
index.js
window.onload = function () {
init();
}
function init() {
initMagnifier();
}
var initMagnifier = (function () {
var oImgWrap = document.getElementsByClassName('img-wrap')[0],
oMagWrap = oImgWrap.getElementsByClassName('mag-wrap')[0],
oMagImg = oMagWrap.getElementsByClassName('mag-img')[0],
magWidth = getStyles(oMagWrap, 'width'),
magHeight = getStyles(oMagWrap, 'height'),
imgX = oImgWrap.offsetLeft,
imgY = oImgWrap.offsetTop;
addEvent(oImgWrap, 'mouseover', function (e) {
showMag(getXY(e).x, getXY(e).y)
oMagWrap.className += ' show';
addEvent(document, 'mousemove', mouseMove);
})
addEvent(oImgWrap, 'mouseout', mouseOut);
function mouseMove(e) {
showMag(getXY(e).x, getXY(e).y, getXY(e).mouseX, getXY(e).mouseY)
}
function mouseOut(e) {
oMagWrap.className = 'mag-wrap';
removeEvent(document, 'mousemove', mouseMove);
}
function getXY(e) {
var e = e || window.event;
return {
x: pagePos(e).X - imgX - magWidth / 2,
y: pagePos(e).Y - imgY - magHeight / 2,
mouseX: pagePos(e).X - imgX,
mouseY: pagePos(e).Y - imgY
}
}
function showMag(x, y, mouseX, mouseY) {
oMagWrap.style.left = x + 'px';
oMagWrap.style.top = y + 'px';
oMagImg.style.left = -x + 'px';
oMagImg.style.top = -y + 'px';
if (mouseX && mouseY) {
if (mouseX < 0 || mouseX > getStyles(oImgWrap, 'width') || mouseY < 0 || mouseY > getStyles(oImgWrap, 'height')) {
oMagWrap.className = 'mag-wrap';
}
}
}
});