效果:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>放大镜</title>
<style type="text/css">
body, div {
margin: 0;
padding: 0;
}
#con {
position: absolute;
top: 50%;
left: 50%;
margin: -150px 0 0 -150px;
width: 300px;
height: 300px;
background: url("img/bg.jpeg") no-repeat;
background-size: 100%;
}
#dec {
display: none;
position: absolute;
top: 50%;
left: 50%;
margin: -150px 0 0 160px;
width: 300px;
height: 300px;
background: url("img/bg.jpeg") no-repeat 0 0;
background-size: 300%;
border-radius: 50%;
}
#box {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
/*background: rgba(0, 0, 0, 0.5);*/
background: #22b909;
opacity: 0.4;
filter: alpha(opacity=40);
cursor: move;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="con"></div>
<div id="dec"></div>
<script type="text/javascript">
var con=document.getElementById('con');
var dec=document.getElementById('dec');
con.onmouseenter=function(e){
this.mx=e.pageX;
// this.x=this.offsetLeft;
// this.y=this.offsetTop;
this.my=e.pageY;
var div=document.getElementById("box");
if(!div){
var div=document.createElement("div");
div.id="box";
this.appendChild(div);
}else{
div.style.display="block";
}
}
con.onmousemove=function(e){
e=e||window.event;
var mask=document.getElementById("box");
if(mask){
move(mask,e,this);
dec.style.display="block";
}
}
function move(mask,e,self){
var w=self.offsetWidth-mask.offsetWidth;
var h=self.offsetHeight-mask.offsetHeight;
var l=e.pageX-self.offsetLeft-mask.offsetWidth/2
var t=e.pageY-self.offsetTop-mask.offsetHeight/2
if(l>=w){
mask.style.left=w+"px";
dec.style.backgroundPositionX=-w*3+"px";
}else if(l<=0){
mask.style.left=0+"px";
dec.style.backgroundPositionX=0+"px";
}else{
mask.style.left=e.pageX-self.offsetLeft-mask.offsetWidth/2+"px";
dec.style.backgroundPositionX=-l*3+"px";
}
if(t>=h){
mask.style.top=h+"px";
dec.style.backgroundPositionY=-h*3+"px";
}else if(t<=0){
mask.style.top=0+"px";
dec.style.backgroundPositionY=0+"px";
}else{
mask.style.top=e.pageY-self.offsetTop-mask.offsetHeight/2+"px";
dec.style.backgroundPositionY=-t*3+"px";
}
}
con.onmouseleave=function(e){
var mask=document.getElementById("box");
if(mask){
dec.style.display="none";
mask.style.display="none";
}
}
</script>
</body>
</html>
网友评论