<!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;
}
.box1 {
position: relative;
margin: auto;
height: 500px;
width: 750px;
border: 2px solid blueviolet;
}
.zhao {
position: absolute;
left: 0;
top: 0;
display: none;
width: 220px;
height: 220px;
cursor: pointer;
background: rgba(239, 176, 39, 0.3);
}
.Xbox {
position: absolute;
top: 0;
left: 0;
width: 315px;
height: 313px;
border: 2px solid #9c9696;
}
.Dbox {
position: absolute;
top: 0;
right: 0;
overflow: hidden;
display: none;
width: 400px;
height: 400px;
border: 2px solid green;
}
.Dbox img{
width: 200%;
height: 200%;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<!-- html -->
<div class="box1">
<!-- 一共需要两个一样但大小不同的图片 -->
<div class="Xbox">
<!-- 小图 -->
<img src="./img/small.png" alt="" width="300" height="300">
<div class="zhao"></div>
</div>
<div class="Dbox">
<!-- 大图 -->
<img src="./img/1big.jpg" alt="" width="600" height="600" class="img">
</div>
</div>
<!-- js -->
<script>
// 获取页面元素
var Xbox = document.querySelector('.Xbox');
var Dbox = document.querySelector('.Dbox');
var zhao = document.querySelector('.zhao');
var box1 = document.querySelector('.box1');
var img=document.querySelector('.img');
// 鼠标移入时让大盒子和遮罩层显示
Xbox.addEventListener('mouseover', function () {
Dbox.style.display = 'block';
zhao.style.display = 'block';
});
Xbox.addEventListener('mouseout', function () {
Dbox.style.display = 'none';
zhao.style.display = 'none';
});
Xbox.addEventListener('mousemove', function (e) {
//1、 获取鼠标在小盒子内的位置
var x = e.pageX - box1.offsetLeft;
var y = e.pageY - box1.offsetTop;
//2、 使光标在遮罩层的中间
x = x - zhao.offsetWidth / 2;
y = y - zhao.offsetHeight / 2;
// 3、边界判断(最大移动距离)zhaoMax是遮罩层最大移动距离
var zhaoMax = Xbox.offsetWidth - zhao.offsetWidth;
if (x <= 0) {
x = 0;
} else if (x >= zhaoMax) {
x = zhaoMax;
}
if (y <= 0) {
y = 0;
} else if (y >= zhaoMax) {
y = zhaoMax;
}
// 设置遮罩层和鼠标一起移动
zhao.style.left = x + 'px';
zhao.style.top = y + 'px';
//4、 大图随遮罩层一起移动
// 大盒子的最大移动距离
var bigMax = img.offsetWidth - Dbox.offsetWidth;
var DboxX = x * bigMax / zhaoMax
var DboxY = y * bigMax / zhaoMax;
img.style.left = -DboxX + 'px';
img.style.top = -DboxY + 'px';
})
</script>
</body>
</html>
仿京东放大镜效果方法一
最新推荐文章于 2024-09-24 11:22:03 发布