首页 > 代码库 > 放大镜效果

放大镜效果

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
<style type="text/css">
#div1 { width:200px; height:300px; position:absolute; display:block; overflow:hidden; left:300px;top:0px;margin:50px 50px;}/*原图*/
#div2 {width:300px; height:300px; position:absolute; display:none; overflow:hidden; left:550px;top:0px; margin:50px 50px;}/*显示框*/
#div1 img{width:200px; height:300px;float:left;}
#div1 span { width:100px; height:100px; background-color:#000; left:0px;top:0px; position:absolute; display:none; filter:alpha(opacity:20); opacity:0.2;}
.show {width:100%;height:100%;background-color:#FFF;position:absolute;z-index:10px;filter:alpha(opacity:10); opacity:0.1;left:0px;top:0px;}
#img2 {position:absolute;left: 0px;top: 0px;}
</style>
<title>图片放大代码</title>
<script type="text/javascript">
window.onload=function ()
{
var oDiv1=document.getElementById(‘div1‘);
var oDiv2=document.getElementById(‘div2‘);
var oShow=oDiv1.getElementsByTagName(‘div‘)[0];
var oSpan=oDiv1.getElementsByTagName(‘span‘)[0];
var oImg=document.getElementById(‘img2‘);
oShow.onmouseover=function()
{
oSpan.style.display=‘block‘;
oDiv2.style.display=‘block‘;//放大部分 显示
};
oShow.onmouseout=function()
{
oSpan.style.display=‘none‘;
oDiv2.style.display=‘none‘;
};
oShow.onmousemove=function(ev)
{
var oEvent=ev||event;
var x=oEvent.clientX-oDiv1.offsetLeft-oSpan.offsetWidth/2;
var y=oEvent.clientY-oDiv1.offsetTop-oSpan.offsetHeight/2;
if(x<0)
{
x=0;
}
else if(x>oShow.offsetWidth-oSpan.offsetWidth)
{
x=oShow.offsetWidth-oSpan.offsetWidth;
}
if(y<0)
{
y=0;
}
else if(y>oShow.offsetHeight-oSpan.offsetHeight)
{
y=oShow.offsetHeight-oSpan.offsetHeight
}
oSpan.style.left=x+‘px‘;
oSpan.style.top=y+‘px‘;

oImg.style.left=x*(oDiv2.offsetWidth-oImg.offsetWidth)/(oShow.offsetWidth-oSpan.offsetWidth)+‘px‘;
oImg.style.top=y*(oDiv2.offsetHeight-oImg.offsetHeight)/(oShow.offsetHeight-oSpan.offsetHeight)+‘px‘;
};
};
</script>
</head>
<body>
<div id="div1"> <img src="http://www.mamicode.com/imag1.jpg" />
<span></span>
<div class="show"></div>
</div>
<div id="div2"><img id="img2" src="http://www.mamicode.com/imag1.jpg" /></div>
</body>
</html>

放大镜效果