发表于: 2023-01-03 21:11:21
0 340
今天完成了一放大镜拖动练习:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大效果</title>
<style>
div {
margin: 0 auto;
position: relative;
width: 400px;
height: 400px;
border: 1px solid #333333;
}
.a {
width: 200px;
}
.mask {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background-color: #FEDE4F;
opacity: .5;
cursor: move;
}
.big {
display: none;
position: absolute;
top: 0;
left: 410px;
width: 500px;
height: 500px;
border: 1px solid #333333;
overflow: hidden;
}
.b {
position: absolute;
top: 0;
left: 0;
width: 600px;
}
</style>
</head>
<div>
<img class="a" src="../js2-DOM/图片/猫.jpg">
<div class="mask"></div>
<div class="big">
<img class="b" src="../js2-DOM/图片/猫.jpg">
</div>
</div>
<script>
var div = document.querySelector('div');
var mask = document.querySelector('.mask');
var big = document.querySelector('.big');
//显示
div.addEventListener('mousemove', function () {
mask.style.display = 'block';
big.style.display = 'block';
})
//隐藏
div.addEventListener('mouseout', function () {
mask.style.display = 'none';
big.style.display = 'none';
})
div.addEventListener('mousemove',function (e){
//(1)先计算出鼠标在盒子内的坐标
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
//(2)减去盒子高度的一半 /2
//(3) 我们mask 移动的距离
var maskX = x - mask.offsetWidth / 2;
var maskY = y - mask.offsetHeight / 2;
// (4)如果x y 坐标 小于了0 就让他停在0 的位置
var maskMax = div.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';
//大图片的移动距离 = 遮挡层移动的距离(maskX/Y) * 大图片最大移动距离 (bigMax) / 遮挡层最大移动距离(maskMax)
var b = document.querySelector('.b'); //获取大图片
var bigMax = b.offsetWidth - big.offsetWidth; //大图片最大移动距离
// 大图片的移动距离 X
var bigX = maskX * bigMax / maskMax;
// 大图片的移动距离 Y
var bigY = maskY * bigMax / maskMax;
b.style.left = -bigX + 'px';
b.style.top = -bigY + 'px';
})
</script>
<body>
</body>
</html>
评论