<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<!--<link rel="stylesheet" href="css/index.css">-->
<style>
img {
display: block;
}
* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
overflow: hidden;
display: none;
}
.big img {
position: absolute;
}
.mask {
width: 100px;
height: 100px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0px;
left: 0px;
cursor: move;
display: none;
}
.small {
position: relative;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="small" id="small">
<img src="图片地址" width="350" alt="" />
<div class="mask" id="mask"></div>
</div>
<div class="big" id="big">
<img src="图片地址" width="800" alt="" id="img" />
</div>
</div>
</body>
<script>
//1 获取节点
var boxObj = document.querySelector('#box');
var smallObj = document.getElementById('small');
var imgsmall = smallObj.firstElementChild;
var mackObj = smallObj.lastElementChild;
var bigObj = document.getElementById('big');
var imgbig = bigObj.firstElementChild;
console.log(mackObj);
// 2 给small绑定鼠标移入事件
smallObj.onmouseenter = function () {
// 2-1 显示mask和大图
mackObj.style.display = 'block';
bigObj.style.display = 'block';
}
// 3 鼠标移出消失
smallObj.onmouseleave = () => {
mackObj.style.display = 'none';
bigObj.style.display = 'none';
}
//4 鼠标移动则让mask跟随
smallObj.onmousemove = (eve) => {
var e = eve || window.event;
// 4-1 获取鼠标的实时位置
let wSx = e.pageX;
let wSy = e.pageY;
// console.log(wSx);
// console.log(wSy);
// 4-2 获取box的left和top值,计算出鼠标相对于small的坐标
let boxLeft = boxObj.offsetLeft;
let boxTop = boxObj.offsetTop;
// console.log(boxLeft);
// console.log(boxTop);
var maskX = wSx - boxLeft - mackObj.offsetWidth / 2;
var maskY = wSy - boxTop - mackObj.offsetHeight / 2;
// 4-3 边界的设置
// 上面的边界
if (maskX < 0) {
maskX = 0;
}
if (maskY < 0) {
maskY = 0;
}
var smallObjWx = smallObj.offsetWidth - mackObj.offsetWidth;
var smallObjHx = smallObj.offsetHeight - mackObj.offsetHeight;
if (maskX > smallObjWx) {
maskX = smallObjWx;
}
if (maskY > smallObjHx) {
maskY = smallObjHx;
}
// 给mask设置位置
mackObj.style.top = maskY + 'px';
mackObj.style.left = maskX + 'px';
//黄色盒子覆盖到哪里,对应的大盒子里图片展示哪里
// mask移动的距离 / mask移动的最大距离 == img移动的距离 / img移动的最大距离
//img移动的距离 = mask移动的距离 / mask移动的最大距离 * img移动的最大距离
let smeentX = imgbig.offsetWidth - bigObj.offsetWidth;
let smeentY = imgbig.offsetHeight - bigObj.offsetHeight;
// 由公式算出 大图的left和top
let lenterX = maskX / smallObjWx * smeentX;
let lenterY = maskY / smallObjHx * smeentY;
// 设置给大图
imgbig.style.top = -lenterY + 'px';
imgbig.style.left = -lenterX + 'px';
console.log(lenterX);
}
</script>
</html>
放大镜效果
最新推荐文章于 2024-11-04 09:11:09 发布