1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
⒉将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
<!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>
.box {
position: relative;
width: 350px;
/* height: 350px; */
}
.small {
width: 350px;
}
.yy {
position: absolute;
top: 0;
left: 0;
width: 250px;
height: 250px;
background-color: yellow;
opacity: 0.5;
border: 1px solid #333;
display: none;
}
.big {
position: absolute;
left: 360px;
top: 0px;
width: 500px;
height: 500px;
overflow: hidden;
display: none;
}
.big>img {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box">
<img src="./p1.webp" alt="" class="small">
<div class="yy"></div>
<div class="big">
<img src="./p1.webp" alt="">
</div>
</div>
<script>
window.addEventListener('load', function () {
var box = document.querySelector('.box');
var yy = document.querySelector('.yy');
var big = document.querySelector('.big');
box.addEventListener('mouseover', function () {
yy.style.display = 'block';
big.style.display = 'block';
})
box.addEventListener('mouseout', function () {
yy.style.display = 'none';
big.style.display = 'none';
})
box.addEventListener('mousemove', function (e) {
var x = e.pageX - box.offsetLeft;
var y = e.pageY - box.offsetTop;
var width = x - yy.offsetWidth / 2;
var height = y - yy.offsetHeight / 2;
if (width <= 0) {
width = 0;
} else if (width >= box.offsetWidth - yy.offsetWidth) {
width = 100;
}
if (height <= 0) {
height = 0;
} else if (height >= box.offsetHeight - yy.offsetHeight) {
height = box.offsetHeight - yy.offsetHeight;
}
yy.style.left = width + 'px';
yy.style.top = height + 'px';
var bigimg = document.querySelector('.big>img');
// 大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
var bigx = width * (bigimg.offsetWidth - big.offsetWidth) / (box.offsetWidth - yy.offsetWidth);
var bigy = height * (bigimg.offsetHeight - big.offsetHeight) / (box.offsetHeight - yy.offsetHeight);
bigimg.style.left = -bigx + 'px';
bigimg.style.top = -bigy + 'px';
})
})
</script>
</body>
</html>
用相对定位在图片右边建一个盒子,通过计算鼠标在 原图片中的移动距离来控制右侧显示的方位。
放大镜