代码改变世界

简单的放大镜效果

2012-03-13 14:05  滴水成兵  阅读(204)  评论(0编辑  收藏  举报

很多电子商务网站都用到放大镜效果,在这写了个简单的效果

View Code
<!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>无标题文档</title>
<style>
*
{ padding:0; margin:0;}
#div1
{ border:1px solid #F6F; position:relative;width:180px; height:180px;}
#div2
{ border:1px solid #F6F; position:relative;top:-180px; left:200px; overflow:hidden;width:300px; height:300px; display:none;}
#mark
{ width:100%; height:100%;background:#000; z-index:3; position:absolute; top:0; left:0;opacity:0;filter:alpha(opacity=0);cursor:move; }
#div1 span
{ width:60px; height:60px; background:yellow; display:block; position:absolute; left:0; top:0; filter:alpha(opacity=50); opacity:0.5;display:none; z-index:2;}
#div2 img
{ position:absolute; top:0; left:0;}
</style>

<script>
window.onload
=function(){
var oDiv1=document.getElementById('div1');
var oDiv2=document.getElementById('div2');
oSpan
=oDiv1.getElementsByTagName('span')[0];
var oMark=document.getElementById('mark');
var oImg2 =document.getElementById('img1');
var _src = oImg2.getAttribute('_src');
var oImg=document.createElement('img');
oDiv2.appendChild(oImg);
oMark.onmouseover
=function(){
oImg.src
= _src;
oSpan.style.display
='block';
oDiv2.style.display
='block';
};
oMark.onmouseout
=function(){
oSpan.style.display
='none';
oDiv2.style.display
='none';

};
oMark.onmousemove
=function(ev){
var ev=ev || window.event;
var l=ev.clientX - oDiv1.offsetLeft - oSpan.offsetWidth/2;
var t=ev.clientY - oDiv1.offsetTop - oSpan.offsetHeight/2;
if(l<0){
l
=0;
}
else if(l>oDiv1.offsetWidth - oSpan.offsetWidth){
l
=oDiv1.offsetWidth - oSpan.offsetWidth;
}
if(t<0){
t
=0;
}
else if(t>oDiv1.offsetHeight - oSpan.offsetHeight){
t
=oDiv1.offsetHeight - oSpan.offsetHeight;
}
oSpan.style.left
=l+'px';
oSpan.style.top
=t+'px';
var scaleX = l/(oDiv1.offsetWidth-oSpan.offsetWidth);
var scaleY = t/(oDiv1.offsetHeight-oSpan.offsetHeight);
oImg.style.left = -scaleX*(oImg.offsetWidth - oDiv2.offsetWidth) + 'px';
oImg.style.top
= -scaleY*(oImg.offsetHeight - oDiv2.offsetHeight) + 'px';

};

}
</script>
</head>

<body>
<div>
<div id="div1">
<img src="b2.jpg" _src="b1.jpg" id="img1"/>
<div id="mark"></div>
<span></span>
</div>
<div id="div2"></div>
</div>

</body>
</html>

需要用到两张等比例不同大小的图....