jQuery放大镜制作
思路:
制作放大镜的核心是当小图存在的盒子中有鼠标移动时,大图存在的盒子出现并使大图可以随着鼠标的移动而移动。鼠标移出小图存在的盒子时,大图存在的盒子消失。
代码
<!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>
body {
margin: 0;
padding: 0;
}
.small {
width: 350px;
float: left;
position: relative;
}
.small img {
width: 350px;
}
.big {
float: left;
width: 500px;
height: 500px;
overflow: hidden;
display: none;
position: relative;
outline: 1px solid red;
}
.mask {
position: absolute;
width: 175px;
height: 175px;
opacity: 0.5;
background-color: yellow;
top: 0;
left: 0;
/* 不再触发事件 */
pointer-events: none;
}
.clearfix::after {
content: "";
display: block;
clear: both;
}
.big img {
position: absolute;
}
</style>
</head>
<body>
<div class="box clearfix">
<div class="small">
<img src="./img/small.png" alt="">
<div class="mask"></div>
</div>
<!--放大区域-->
<div class="big">
<img src="./img/big.jpg" alt="">
</div>
</div>
</body>
<script src="./jquery.js"></script>
<script>
//鼠标进入small,显示big
$(".small").mouseenter(function() {
$(".big").show()
})
//鼠标离开small,隐藏mask
$(".small").mouseleave(function() {
$(".big").hide()
})
//鼠标移动时,mask跟着鼠标移动
$(".small").mousemove(function(e) {
// mask移动的距离=鼠标移动的距离-mask盒子的一半
var left = event.pageX - $(".mask").outerWidth() / 2;
var top = event.pageY - $(".mask").outerHeight() / 2;
// mask移动的最小距离
left = left < 0 ? 0 : left;
top = top < 0 ? 0 : top;
// mask向右移动最大的距离=small的宽度 - mask的宽度
var width = $(".small").outerWidth() - $(".mask").outerWidth();
// mask向下移动最大的距离=small的高度 - mask的高度
var height = $(".small").outerHeight() - $(".mask").outerHeight();
left = left > width ? width : left;
top = top > height ? height : top;
// 将left和top给mask盒子
$(".mask").css({
"left": `${left}px`,
"top": `${top}px`
})
// 让右边的大图根据遮罩的移动距离进行移动
// 大图移动的最大距离
var imgwidth = $(".big").outerWidth() - $(".big img").outerWidth();
var imgheight = $(".big").outerHeight() - $(".big img").outerHeight();
console.log(imgwidth);
// 图片的移动距离 = mask的移动距离乘两者最大移动距离的比例
var imgleft = left * imgwidth / width;
var imgtop = top * imgheight / height;
// console.log(imgleft);
$(".big img").css({
"left": `${imgleft}px`,
"top": `${imgtop}px`
})
})
</script>
</html>