<!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>
</head>
<!-- css样式 -->
<style>
* {
margin: 0;
padding: 0;
}
.bao {
position: relative;
width: 800px;
height: 600px;
background: rgb(222, 222, 247);
}
.small {
position: relative;
overflow: hidden;
width: 310px;
height: 310px;
border: 2px solid red;
}
.big {
position: absolute;
top: 0;
right: 0;
display: none;
overflow: hidden;
width: 450px;
height: 450px;
border: 2px solid green;
}
.zhao {
position: absolute;
top: 0;
left: 0;
display: none;
width: 200px;
height: 200px;
background: rgba(232, 207, 48, 0.5);
}
.img {
width: 200%;
height: 200%;
}
</style>
<body>
<!-- html -->
<div class="bao">
<!-- 一共需要两个一样但大小不同的图片 -->
<div class="small">
<!-- 小图 -->
<img src="./img/small.png" alt="">
<div class="zhao"></div>
</div>
<div class="big">
<!-- 大图 -->
<img src="./img/1big.jpg" alt="" class="img" width="600" height="600">
</div>
</div>
<!-- js -->
<script>
// 获取元素
var small = document.querySelector('.small');
var big = document.querySelector('.big');
var zhao = document.querySelector('.zhao');
var bao = document.querySelector('.bao');
var img = document.querySelector('.img');
// 鼠标移入让大盒子和遮罩层显示
small.addEventListener('mouseover', function () {
// 显示
zhao.style.display = 'block';
big.style.display = 'block';
small.addEventListener('mouseout', function () {
// 隐藏
zhao.style.display = 'none';
big.style.display = 'none';
});
});
// 移动遮罩层
small.addEventListener('mousemove', function (e) {
// 求小盒子减去遮罩层的(x, y)
var maxLeft = small.offsetWidth - zhao.offsetWidth;
var maxTop = small.offsetHeight - zhao.offsetHeight;
var x = e.clientX - small.offsetLeft - zhao.offsetWidth / 2;
var y = e.clientY - small.offsetTop - zhao.offsetHeight / 2;
// 边界判断
// 限制左边和上边
x = x <= 0 ? 0 : x;
y = y <= 0 ? 0 : y;
// 限制右边和上边
x = x >= maxLeft ? maxLeft : x;
y = y >= maxTop ? maxTop : y;
zhao.style.left = x + 'px';
zhao.style.top = y + 'px';
// 让大盒子的图片随遮罩层移动
var imgLeft = x / maxLeft * (img.offsetWidth - big.offsetWidth);
var imgTop = y / maxTop * (img.offsetHeight - big.offsetHeight);
})
</script>
</body>
</html>
仿京东放大镜效果方法二
最新推荐文章于 2024-08-18 10:54:05 发布