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>
.box {
width: 450px;
height: 450px;
margin: 50px 0 0 30px;
border: 1px solid #ebebeb;
position: relative;
}
.mask {
display: none;
width: 300px;
height: 300px;
background-color: yellow;
opacity: 0.5;
position: absolute;
left: 0;
top: 0;
cursor: move;
}
.bigBox {
display: none;
width: 600px;
height: 600px;
border: 1px solid #ebebeb;
position: absolute;
left: 460px;
top: 0;
overflow: hidden;
}
.bigImg {
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="box">
<img src="./images/be8ecd190a639396.jpg" alt="">
<div class="mask"></div>
<div class="bigBox">
<img src="./images/be8ecd190a639396 (1).jpg" alt="" class="bigImg">
</div>
</div>
<script>
var box = document.querySelector('.box');
var mask = document.querySelector('.mask');
var bigBox = document.querySelector('.bigBox');
var bigImg = document.querySelector('.bigImg');
box.addEventListener('mouseover', function () {
mask.style.display = 'block';
bigBox.style.display = 'block';
})
box.addEventListener('mouseout', function () {
mask.style.display = 'none';
bigBox.style.display = 'none';
})
box.addEventListener('mousemove', function (e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var maskX = x - mask.offsetWidth / 2;
var maskY = y - mask.offsetHeight / 2;
var maskMax = this.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.left = maskX + 'px';
mask.style.top = maskY + 'px';
var bigMax = bigImg.offsetWidth - bigBox.offsetWidth;
var bigX = maskX * bigMax / maskMax;
var bigY = maskY * bigMax / maskMax;
bigImg.style.left = -bigX + 'px';
bigImg.style.top = -bigY + 'px';
})
</script>
</body>
</html>
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭