* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask {
width: 175px;
height: 175px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small {
position: relative;
}
.box img {
vertical-align: top;
}
#bigBox>img {
/*是让里面的图片脱标,为的就是让里面的图片进行一个移动*/
position: absolute;
}
// 三层需求
// 需求1:鼠标移入盒子(small)遮罩显示,显示大盒子,移出小盒子,遮罩隐藏,隐藏大盒子
// 需求2:鼠标在小盒子中移动,遮罩要跟着跑:鼠标应该在遮罩的中间
// 需求3:遮罩移动的时候,大盒子中的大图应该按比例反向移动
// 获取相关数据
let box = document.getElementById('box');
let small = document.getElementById('smallBox');
let big = document.getElementById('bigBox');
let mask = document.getElementById('mask');
let img = document.getElementById('bigImg');
// 需求1:鼠标移入移出事件,修改样式
small.onmouseover = function () {
mask.style.display = 'block';
big.style.display = 'block';
};
small.onmouseout = function () {
mask.style.display = '';
big.style.display = '';
}
// 需求2:鼠标在小盒子中移动,遮罩要跟着跑:鼠标应该在遮罩的中间
/*
思路分析
1. 给小盒子添加鼠标移动事件:onmousemove
2. 事件处理
2.1 获取鼠标的位置:事件对象,e.pageX 和 e.pageY
2.2 计算遮罩的left的值:e.pageX - box.offsetLeft - mask.offsetWidth / 2
2.3 安全:遮罩不能移出小盒子
* x的值不能小于0:小于最多等于0,不能超过175(small.offsetWidth - mask.offsetWidth):最多175
* y的值不能小于0:小于最多等于0,不能超过175(small.offsetHeight - mask.offsetHeight):最多175
2.4 理论上可以给遮罩修改位置
*/
// 1. 给小盒子添加鼠标移动事件:onmousemove
small.onmousemove = function (e) {
// 2. 事件处理
// 2.1 获取鼠标的位置:事件对象,e.pageX 和 e.pageY
// 2.2 计算遮罩的left的值:e.pageX - box.offsetLeft - mask.offsetWidth / 2
let x = e.pageX - box.offsetLeft - mask.offsetWidth / 2;
let y = e.pageY - box.offsetTop - mask.offsetHeight / 2;
// 2.3 安全:遮罩不能移出小盒子
// * x的值不能小于0:小于最多等于0,不能超过175(small.offsetWidth - mask.offsetWidth):最多175
if (x < 0) x = 0; // 如果{}中只有一行代码,可以省略{}
let maxX = small.offsetWidth - mask.offsetWidth;
if (x > maxX) x = maxX;
// * y的值不能小于0:小于最多等于0,不能超过175(small.offsetHeight - mask.offsetHeight):最多175
if (y < 0) y = 0; // 如果{}中只有一行代码,可以省略{}
let maxY = small.offsetHeight - mask.offsetHeight;
if (y > maxY) y = maxY;
// console.log(x, y);
// 2.3 理论上可以给遮罩修改位置
mask.style.left = x + 'px';
mask.style.top = y + 'px';
// 需求3:遮罩移动的时候,大盒子中的大图应该按比例反向移动
/*
思路分析:遮罩移动多少,大图反向移动多少
1. 算出图片移动与遮罩移动的比例
2. 大图的移动 = 遮罩移动的距离 * 比例
*/
// 1. 算出图片移动与遮罩移动的比例
let biliX = (img.offsetWidth - big.offsetWidth) / (small.offsetWidth - mask.offsetWidth);
let biliY = (img.offsetHeight - big.offsetHeight) / (small.offsetHeight - mask.offsetHeight);
console.log(img.offsetWidth, big.offsetWidth, small.offsetWidth, mask.offsetWidth);
console.log(img.offsetHeight, big.offsetHeight, small.offsetHeight, mask.offsetHeight);
// console.log(biliX, biliY);
// 2. 大图的移动 = 遮罩移动的距离 * 比例
img.style.left = - x * biliX + 'px';
img.style.top = - y * biliY + 'px';
}
一键复制
编辑
Web IDE
原始数据
按行查看
历史