jQuery实现放大镜效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery3.min.js"></script>
<style>
.box{
width: 180px;
height: 180px;
float: left;
position: relative;
}
.box .mark{
width: 100px;
height: 100px;
background: #ff0;
opacity: .5;
position: absolute;
left: 0;
top: 0;
display: none;
}
.boxed{
width: 500px;
height: 500px;
float: left;
left: 250px;
top: 50px;
overflow: hidden;
position: relative;
display: none;
}
.boxed img{
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box">
<img src="./images/b2.jpg" alt="">
<span class="mark"></span>
</div>
<div class="boxed">
<img src="./images/b1.jpg">
</div>
</body>
<script>
//鼠标移入显示大图和遮罩层,鼠标移出隐藏
$(".box").hover(function(){
$(".mark").css("display","block");
$(".boxed").css("display","block");
},function(){
$(".mark").css("display","none");
$(".boxed").css("display","none");
})
$(".box").mousemove(function(ev){
var ev = ev || event;
//获取遮罩层左侧到盒子左侧的距离
var L = ev.clientX - $(".box").offset().left - $("span").width()/2;
//获取遮罩层上侧到盒子上边界的距离
var T = ev.clientY - $(".box").offset().top - $("span").height()/2;
//判断遮罩层的边界,如果超过盒子左边则赋值为0;如果超过盒子右侧则赋值盒子临界值(右侧)
if(L < 0){
L = 0;
}else if(L > $(".box").width() - $("span").width()){
L = $(".box").width() - $("span").width();
}
if(T < 0){
T = 0;
}else if(T > $(".box").height() - $("span").height()){
T = $(".box").height() - $("span").height();
}
$("span").css("left",L + "px");//赋值遮罩层移动的左边距
$("span").css("top",T + "px");//赋值遮罩层移动的上边距
var numL = $(".boxed img").width()/$(".box img").width();//计算大图与小图的比例
$(".boxed img").css("left","-"+numL*L + "px");//赋值大图移动的左边距
$(".boxed img").css("top","-"+numL*T + "px");//赋值大图移动的上边距
})
</script>
</html>