<!DOCTYPE HTML>
<html
lang="en-US">
<head>
<meta
charset="UTF-8">
<title>原生Js结合html5做出放大镜的效果</title>
<style>
img{
margin:100px
500px;
}
div{
width:200px;
height:200px;
display:none;
border:1px
solid
#ccc;
border-radius:100px;
z-index:1000;
pointer-events:none;
}
</style>
</head>
<body>
<img
src="http://d.hiphotos.baidu.com/image/w%3D2048/sign=529c3afe39c79f3d8fe1e3308e99cc11/7a899e510fb30f24d9069302ca95d143ad4b0316.jpg"
onload="core(this)"></img>
<div
id="showImg"></div>
<script>
//图片加载完成之后,触发这个方法
function
core(obj){
//加载完成之后,就将图片大小设置完成
obj.width = "400";
var new_div =
document.getElementById("showImg");
//现在图片的大小
var width_changed =
obj.width;
var height_changed = obj.height;
//得到原图的真正的宽高
var img =
new Image();
img.src = obj.src;
var width_start = "";
var
height_start = "";
//需要在加载完成之后再获取到原图的宽高
img.onload =
function(){
width_start = img.width;
height_start =
img.height;
//在最开始就设置背景图片
new_div.style.backgroundImage =
"url("+this.src+")";
obj.onmousemove =
function(e){
obj.style.opacity =
0.7;
//获取鼠标的位置(获取相对位置)
//鼠标在图片上的位置
var pageX_changed = e.pageX
- 500;
var pageY_changed = e.pageY -
100;
//根据鼠标在改变宽高的图片的位置,计算鼠标在原图的位置
var pageX_start =
parseInt(pageX_changed/width_changed*width_start);
var pageY_start =
parseInt(pageY_changed/height_changed*height_start);
//定位一下div
new_div.style.display
= "block";
new_div.style.position = "absolute";
new_div.style.left
= parseInt(e.pageX - 100) + "px";
new_div.style.top = parseInt(e.pageY -
100) + "px";
new_div.style.overflow =
"hidden";
new_div.style.width = "200px";
new_div.style.height =
"200px";
//设置div的背景图片的位置
new_div.style.backgroundPosition =
-(pageX_start-100) + "px " + -(pageY_start-100) +
"px";
new_div.style.backgroundRepeat =
"no-repeat";
}
obj.onmouseout =
function(){
document.getElementById("showImg").style.display =
"none";
obj.style.opacity =
1;
}
};
}
</script>
</body>
</html>