<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQ放大镜</title>
<style>
*{
padding: 0;
margin: 0;
}
.outer{
width: 200px;
margin: 80px auto;
position: relative;
}
.big{
width: 180px;
height: 180px;
position: absolute;
border-radius: 100%;
box-shadow: 0 0 0 7px rgba(255,255,255,0.8),0 0 7px 7px rgba(0,0,0,0.3),inset 0 0 40px 2px rgba(0,0,0,0.3);
background: url(iphone.jpg) no-repeat;
display: none;
}
.small{
display: block;
}
</style>
</head>
<body>
<div class="outer">
<div class="big"></div>
<img src="iphone.jpg" alt="" class="small" width="200px">
</div>
<script type="text/javascript" src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
// 定义实际图片的大小
var imgWidth = 0;
var imgHeight = 0;
$(".small").load(function(){
// 创建图片对象
var imgObj = new Image();
imgObj.src = $(this).attr("src");
imgWidth =imgObj.width;
imgHeight = imgObj.height;
$(".outer").mousemove(function(e){
var outerOffset = $(this).offset();
var mx = e.clientX - outerOffset.left;
var my = e.clientY - outerOffset.top;
// 放大镜的显示与隐藏
if(mx > 0 && mx < $(this).width() && my > 0 && my < $(this).height()){
$(".big").fadeIn(100);
}else{
$(".big").fadeOut(100);
}
// 判断放大镜可显示
if($(".big").is(":visible")){
var rx = Math.round(mx/$(".small").width()*imgWidth - $(".big").width()/2)*-1;
var ry = Math.round(my/$(".small").height()*imgHeight - $(".big").height()/2)*-1;
var bgp = rx + "px " + ry + "px";
// 放大镜跟随鼠标
var gx = mx - $(".big").width()/2;
var gy = my - $(".big").height()/2;
$(".big").css({
left:gx,
top:gy,
backgroundPosition:bgp,
})
}
})
})
})
</script>
</body>
</html>
jq放大镜
最新推荐文章于 2021-06-19 18:20:00 发布