首页 > 代码库 > Javascript:实操---放大镜效果(2)
Javascript:实操---放大镜效果(2)
CSS部分
<style type="text/css">
/* body{
padding: 10px;
} */
#minWrap{
width: 350px;
height: 350px;
border: 1px solid #ccc;
position: relative;
}
#slider{
height: 175px;
width: 175px;
background-color: yellow;
opacity: 0.3;
position: absolute;
left: 0;
top: 0;
display: none;
}
#maxWrap{
display: none;
position: absolute;
left: 370px;
width: 400px;
height: 400px;
border: 1px solid #ccc;
overflow: hidden;
top: 8px;
}
#maxWrap img{
position: absolute;
}
</style>
JS部分
<script type="text/javascript">
window.onload=function (){
var minWrap=document.getElementById("minWrap");
var oSlider=document.getElementById("slider");
var maxWrap=document.getElementById("maxWrap");
var maxImg=maxWrap.children[0];
minWrap.onmousemove=function (ev){
oSlider.style.display="block";
maxWrap.style.display="block";
var oEvent=ev||window.event;
var x=oEvent.clientX-oSlider.offsetWidth/2-minWrap.offsetLeft;
var y=oEvent.clientY-oSlider.offsetHeight/2-minWrap.offsetTop;
if (x>=minWrap.clientWidth-oSlider.offsetWidth){
x=minWrap.clientWidth-oSlider.offsetWidth;
}
else if (x<=0){
x=0;
}
if (y>=minWrap.clientHeight-oSlider.offsetHeight){
y=minWrap.clientHeight-oSlider.offsetHeight;
}
else if (y<=0){
y=0;
}
oSlider.style.left=x+"px";
oSlider.style.top=y+"px";
var scaleX=x/(minWrap.clientWidth-oSlider.offsetWidth);
var scaleY=y/(minWrap.clientHeight-oSlider.offsetHeight);
maxImg.style.left=-scaleX*(maxImg.offsetWidth-maxWrap.offsetWidth)+"px";
maxImg.style.top=-scaleY*(maxImg.offsetHeight-maxWrap.offsetHeight)+"px";
}
minWrap.onmouseout=function (){
oSlider.style.display="none";
maxWrap.style.display="none";
}
}
</script>
HTML部分
<div id="minWrap">
<img src="http://www.mamicode.com/min.jpg" >
<div id="slider"></div>
</div>
<div id="maxWrap">
<img src="http://www.mamicode.com/max.jpg" >
</div>