需求:
1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
实现原理:
1.设立一大一小两个盒子,盒子中放置图片,右边盒子中的图片设置放大倍数,左边的遮罩层与右边大盒子默认隐藏显示。
2.位左边的盒子设置鼠标移入监听,当鼠标移入时显示大盒子,并设置鼠标移动事件将鼠标在盒子内的坐标赋给遮罩层,使得右边盒子对应显示。
<!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 type="text/css">
* {
margin: 0;
padding: 0;
}
#banner{
margin-top: 50px;
margin-left: 100px;
}
#show {
width: 400px;
height: 400px;
border: 1px solid #DDDDDD;
cursor: move;
position: relative;
}
.smallImg {
width: 100%;
height: 100%;
}
.fullShow{
display: none;
width: 250px;
height: 250px;
background-color: coral;
position: absolute;
top: 0;
left: 0;
opacity: 0.5;
}
.bigShow{
display: none;
width: 600px;
height: 600px;
border: 1px solid #DDDDDD;
position: absolute;
left: 440px;
overflow: hidden;
top: 0;
}
.bigImg{
width: 240%;
height: 240%;
position: relative;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="banner">
<div id="show">
<img class="smallImg" src="./R-C.png" />
<div class="fullShow"></div>
<div class="bigShow">
<img class="bigImg" src="./R-C.png" >
</div>
</div>
</div>
<script>
window.addEventListener('load', function() {
var show = document.querySelector('#show');
var fullShow = document.querySelector('.fullShow');
var bigShow = document.querySelector('.bigShow');
var bigImg = document.querySelector('.bigImg');
show.addEventListener('mouseover', function() {
fullShow.style.display = 'block';
bigShow.style.display = 'block';
})
show.addEventListener('mouseout', function() {
fullShow.style.display = 'none';
bigShow.style.display = 'none';
})
show.addEventListener('mousemove', function(e) {
var moveX = e.pageX - show.offsetLeft;
var moveY = e.pageY - show.offsetTop;
var sMoveMax = show.offsetWidth - fullShow.offsetWidth;
var sHalf = fullShow.offsetWidth / 2;
var bMoveX = moveX * bigShow.offsetWidth / show.offsetWidth;
var bMoveY = moveY * bigShow.offsetWidth / show.offsetWidth;
if (moveX <= sHalf) {
fullShow.style.left = 0;
} else if (moveX >= sMoveMax + sHalf) {
fullShow.style.left = sMoveMax + sHalf;
} else {
fullShow.style.left = moveX - sHalf + 'px';
}
if (moveY <= sHalf) {
fullShow.style.top = 0;
} else if (moveY >= sMoveMax + sHalf) {
fullShow.style.top = sMoveMax + sHalf;
} else {
fullShow.style.top = moveY - sHalf + 'px';
}
bigImg.style.left = -bMoveX + 'px';
bigImg.style.top = -bMoveY + 'px';
})
})
</script>
</body>
</html>
效果展示:
QQ录屏20230114182025