js放大镜
Posted cuter、
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js放大镜相关的知识,希望对你有一定的参考价值。
<!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>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.small-img {
position: relative;
width: 262px;
height: 392px;
margin: 100px;
border: 1px solid #ccc;
}
.small-img img {
width: 260px;
}
.big-img {
display: none;
position: absolute;
top: 50px;
left: 600px;
width: 450px;
height: 500px;
border: 1px solid #ccc;
overflow: hidden;
}
.mask {
display: none;
width: 40px;
height: 40px;
background-color: yellow;
opacity: .3;
cursor: move;
position: absolute;
top: 0;
left: 0;
}
#bigimg {
position: absolute;
left: 0;
top: 0;
width: 650px;
height: 975px;
}
</style>
</head>
<body>
<div class="box">
<div class="small-img">
<img src="img/gulinazha.jpg" alt="">
<div class="mask"></div>
</div>
<div class="big-img">
<img src="img/gulinazha.jpg" alt="" id="bigimg">
</div>
</div>
<script src="jd.js"></script>
</body>
</html>
js
window.addEventListener('load', function() {
var smallimg = document.querySelector('.small-img');
var mask = document.querySelector('.mask');
var bigimg = document.querySelector('.big-img');
var bigimgimg = document.getElementById('bigimg');
smallimg.addEventListener('mouseover', function() {
mask.style.display = 'block';
bigimg.style.display = 'block';
})
smallimg.addEventListener('mouseout', function() {
mask.style.display = 'none';
bigimg.style.display = 'none';
})
smallimg.addEventListener('mousemove', function(e) {
var x = e.pageX - smallimg.offsetLeft;
var y = e.pageY - smallimg.offsetTop;
console.log(mask.style.left, mask.style.top);
//最大X移动距离
var maskX = x - mask.offsetWidth / 2;
var maskY = y - mask.offsetHeight / 2;
var maskMaxX = smallimg.offsetWidth - mask.offsetWidth;
var maskMaxY = smallimg.offsetHeight - mask.offsetHeight;
if (maskX < 0) {
maskX = 0;
} else if (maskX > maskMaxX) {
maskX = maskMaxX;
}
if (maskY < 0) {
maskY = 0;
} else if (maskY > maskMaxY) {
maskY = maskMaxY;
}
mask.style.left = maskX + 'px';
mask.style.top = maskY + 'px';
//大盒子
var bigimgMaxX = bigimgimg.offsetWidth - bigimg.offsetWidth;
var bigimgMaxY = bigimgimg.offsetHeight - bigimg.offsetHeight;
var bigx = maskX * bigimgMaxX / maskMaxX;
var bigy = maskY * bigimgMaxY / maskMaxY;
bigimgimg.style.left = -bigx + 'px';
bigimgimg.style.top = -bigy + 'px';
console.log(bigimgimg.style.top);
})
})
以上是关于js放大镜的主要内容,如果未能解决你的问题,请参考以下文章