jQuery实现 图片的局部放大效果

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="images/jquery-1.8.2.min.js" type="text/javascript"></script>
<style type="text/css" >
#bigimg { position:absolute;display:none; overflow:hidden; height:400px; width:400px;margin-left:200px;margin-top:-20px; }
#smalldiv{position:absolute; display:none;}
</style>
<script type="text/javascript">
$(function () {
var count = 0;

$("#img").mousemove(function (e) {
var smalldiv = $("#smalldiv");
var ZoomSizeWidth = $("#img1").width() / $("#img_zoom").width(); //宽放大的倍数
var ZoomSizeHeight = $("#img1").height() / $("#img_zoom").height();//高放大的倍数
$("#bigimg").show();
smalldiv.show();
var mouseX = e.pageX + 5;
var mouseY = e.pageY + 5;


if (e.pageX < $(this).offset().left + smalldiv.width() / 2) {//当鼠标的X坐标小于图片与div遮罩层的x坐标和是divx=0;
divX = 0;
}
else if (e.pageX > $(this).offset().left + smalldiv.width() / 2 && e.pageX < $(this).offset().left + $(this).width() - smalldiv.width() / 2) {//鼠标的X坐标在图片内部并且小于图片最右边的X坐标
divX = e.pageX - $(this).offset().left - smalldiv.width() / 2;
}
else if (e.pageX > $(this).offset().left + $(this).width() - smalldiv.width() / 2) {//鼠标的X坐标大于图片的最右边的X坐标 (Y轴同理)
divX = $(this).width() - smalldiv.width();
}

if (e.pageY < $(this).offset().top + smalldiv.height() / 2) {
divY = 0;
}
else if (e.pageY > $(this).offset().top + smalldiv.height() / 2 && e.pageY < $(this).offset().top + $(this).height() - smalldiv.height() / 2) {
divY = e.pageY - $(this).offset().top - smalldiv.height() / 2;
}
else if (e.pageY > $(this).offset().top - smalldiv.height()) {
divY = $(this).height() - smalldiv.height();
}

$("#bigimg").css("top", mouseY).css("left", mouseX);
smalldiv.css("top", divY).css("left", divX);
smalldiv.appendTo("#img");
var tempX = smalldiv.offset().left - $(this).offset().left;//通过对大图的位置偏移来起到放大的效果
var tempY = smalldiv.offset().top - $(this).offset().top;
$("#img1").css("top", -tempY * ZoomSizeHeight).css("left", -tempX * ZoomSizeWidth);
});

$("#img").mouseleave(function (e) {
$("#smalldiv").hide();
$("#bigimg").hide();
});


})
</script>
</head>
<body>
<div id="img" style=" width:200px; height:200px;margin-left:200px; position:relative; margin-top:30px"><img alt="图片" src="images/Desert.jpg" id="img_zoom" width="200" height="200"/></div>
<div id="bigimg" ><img alt="放大后图片" id="img1" src="images/Desert.jpg" width="800px" height="800px" style="position:absolute" /></div>
<div id="smalldiv" style="width:50px; background-color: rgba(0,0,0,0.5); height:50px; border:1px solid gray; "></div>
</body>
</html>

 

文章摘自:http://blog.csdn.net/kai161/article/details/9384375

posted @ 2014-11-07 09:58  無雄  阅读(1021)  评论(0编辑  收藏  举报