放大镜 2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。 |
原理
一张小图片,一张大图片,通过获取鼠标距离box左上角的距离来获取相应的大图片的width和height,同时溢出隐藏实现放大效果
<!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;
}
.finger {
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
background-color: yellow;
opacity: 0.5;
border: 1px solid #333;
display: none;
}
.small {
height: 400px;
width: 400px;
}
.big {
position: absolute;
left: 360px;
top: 0px;
width: 600px;
height: 600px;
overflow: hidden;
display: none;
}
.big img {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box" id="box">
<img src="https://icweiliimg1.pstatp.com/weili/bl/260506113224737018.jpg" alt="" class="small">
<div class="finger" id="finger"></div>
<div class="big" id="big">
<img src="https://icweiliimg1.pstatp.com/weili/bl/260506113224737018.jpg" alt="" class="bigg">
</div>
</div>
<script>
window.addEventListener('load', function () {
var box = document.querySelector('.box')
var finger = document.querySelector('.finger')
var big = document.querySelector('.big')
var bigg = document.querySelector('.bigg')
box.addEventListener('mouseover', function () {
finger.style.display = 'block';
big.style.display = "block"
})
box.addEventListener('mouseout', function () {
finger.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 fingerX = x - finger.offsetWidth / 2;
var fingerY = y - finger.offsetHeight / 2
var maxWidth = box.offsetWidth - finger.offsetWidth;
var maxHeight = box.offsetHeight - finger.offsetHeight;
if (fingerX <= 0) {
fingerX = 0;
} else if (fingerX >= maxWidth) {
fingerX = maxWidth;
}
if (fingerY <= 0) {
fingerY = 0;
} else if (fingerY >= maxHeight) {
fingerY = maxHeight;
}
finger.style.left = fingerX + 'px';
finger.style.top = fingerY + 'px';
var boxWidth = box.offsetWidth - big.offsetWidth;
var boxHeight = box.offsetHeight - big.offsetHeight;
var bigX = fingerX * boxWidth / maxWidth;
var bigY = fingerY * boxHeight / maxHeight;
bigg.style.left = (-bigX) + 'px';
bigg.style.top = (-bigY) + 'px';
})
})
</script>
</body>
</html>