1,在html页面引入jquery-1.11.3.js文件
2,编写js文件然后引入html页面
/*
* 功能:放大镜
* 参数:
* elem 指最外层的元素
* pic 指图片路径
* w 指图片宽度
* h 指图片高度
* b 指图片的比例
*/
function Scale( elem, pic, w, h, b ){
this.elem = elem;
this.pic = pic;
this.w = w;
this.h = h;
this.b = b;
this.init();
}
Scale.prototype = {
init : function(){
// 创建节点
// 创建小图片div节点
var small = $("<div></div>");
this.elem.append( small );
// 小图片div中,有img
var smallImg = $("<img />");
smallImg.attr({"src":this.pic}).css({"width":this.w, "height":this.h});
small.append( smallImg );
// 小图片上的遮罩
var mask = $("<div></div>");
mask.css({"width":this.w, "height":this.h, "background":"rgba(0,0,0,.6)"});
small.append( mask );
// 小图片上的镜子
var glass = $("<div></div>");
glass.css({"width":this.w/this.b, "height":this.h/this.b, "overflow":"hidden", "display":"none"});
small.append( glass );
// 小图片上的镜子中的图片
var glassImg = $("<img />");
glassImg.attr({"src":this.pic}).css({"width":this.w, "height":this.h});
glass.append( glassImg );
// 创建大图片div节点
var big = $("<div></div>");
big.css({"width":this.w, "height":this.h, "left":this.w+10, "overflow":"hidden", "display":"none"});
this.elem.append( big );
// 大图片div中,有img
var bigImg = $("<img />");
bigImg.attr({"src":this.pic}).css({"width":this.w*this.b, "height":this.h*this.b});
big.append( bigImg );
// 鼠标在小图片div上移动事件
this.glass = glass;
this.glassImg = glassImg;
this.bigImg = bigImg;
this.big = big;
small.bind("mousemove", this.move.bind(this));
small.bind("mouseenter", this.enter.bind(this));
small.bind("mouseleave", this.leave.bind(this));
},
move : function(e){
var x = e.clientX - this.elem.offset().left;
var y = e.clientY - this.elem.offset().top;
// 居中
x -= this.w/this.b/2;
y -= this.h/this.b/2;
// 边界
if( x<0 ) x=0;
if( y<0 ) y=0;
if( x>this.w-this.w/this.b ) x=this.w-this.w/this.b;
if( y>this.h-this.h/this.b ) y=this.h-this.h/this.b;
// 坐标更新
this.glass.css({"left":x, "top":y});
this.glassImg.css({"left":-x, "top":-y});
this.bigImg.css({"left":-x*this.b, "top":-y*this.b});
},
enter : function(){
this.glass.stop().fadeIn();
this.big.stop().fadeIn();
},
leave : function(){
this.glass.stop().fadeOut();
this.big.stop().fadeOut();
}
}
3,html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{
position: relative;
}
#div1 *{
position: absolute;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
<script type="text/javascript" src="jquery-1.11.3.js" ></script>
<script type="text/javascript" src="Scale.js" ></script>
<script>
new Scale( $("#div1"), "bg.jpg", 700, 700, 5 );
</script>