首先我们要准备两张不同大小的图片,用一个盒子来装入图片和遮罩层,另一个盒子来装入放大的图片
HTML代码部分如下:
<body>
<div class="glasswrapper">
<div id="glass" class="glass"> </div>
<img src="../images/3.jpg" alt="" class="img">
</div>
<div class="bigwrapper">
<img src="../images/3.jpg" alt="" class="bigImg">
</div>
</body>
对于CSS部分如下:
<style>
.img {
height: 200px;
width: 200px;
}
/* 放大镜 */
.glass {
width: 100px;
height: 100px;
background-color: yellowgreen;
position: absolute;
opacity: 0.2;
display: none;
}
/* 放大 */
.bigwrapper {
position: relative;
width: 500px;
height: 500px;
background-color: #fff;
border-radius: 10px
overflow: hidden;
}
/* 放大的图片 */
.bigImg {
width: 2000px;
position: absolute;
display: none;
}
.glasswrapper {
float: left;
clear:both;
height: 200px;
width: 200px;
position: relative;
}
</style>
对于放大图片的盒子,明显放大的图片是溢出的所以要以overflow:hidden给它干掉,后续也会得到我们想要的放大镜的效果。
对于JavaScript部分:
window.onload = function () {
//获取图片和放大镜的盒子
let box = document.querySelector(".box");
let glasswrapper = document.querySelector(".glasswrapper");
let img = document.querySelector("img")
//获取放大图
let bigImg = document.querySelector(".bigImg");
//捕获放大镜
let glass = document.querySelector(".glass");
//移入图片显示放大镜和放大图
glasswrapper.onmousemove = function (e) {
//获取鼠标的坐标
let y = e.clientY;
let x = e.clientX;
let glassX = 0;
let glassY = 0;
if (x < 50) {
glassX = 50;
}
else if (x > 150) {
glassX = 150;
}
else {
glassX = x;
}
if (y < 50) {
glassY = 50;
}
else if (y > 150) {
glassY = 150;
}
else {
glassY = y;
}
glass.style.top = glassY - 50 + "px";
glass.style.left = glassX - 50 + "px";
//扩大图的位置
bigImg.style.left = -9 * x + "px"
bigImg.style.top = -9* y + "px"
}
glasswrapper.onmouseout = function () {
glass.style.display = "none";
bigImg.style.display = "none";
}
glasswrapper.onmouseover = function () {
glass.style.display = "block";
bigImg.style.display = "block";
}
}
</script>
对于小盒子的边界问题,我们需要在盒子上设置一个相对定位。鼠标在遮罩的中央坐标为(50,,50)对于当鼠标的坐标小于50或者大于150判定为越界x轴和y轴如此
对于遮罩层,我们需要在鼠标移动到盒子内部才显示。鼠标移出盒子遮罩层消失。我们应该注意原图和放大图之间的放大倍数关系。来判断放大图的位置。