
js代码
var smallWrap=document.getElementById(‘smallWrap‘);
var swWidth=smallWrap.clientWidth;
var swHeight=smallWrap.clientHeight;
var bigWrap=document.getElementById(‘bigWrap‘);
var ratio=2.28;
smallWrap.onmouseover=function(event){
var magnifier=document.createElement(‘div‘);
magnifier.id=‘magnifier‘;
smallWrap.appendChild(magnifier);
setPos(event);
}
smallWrap.onmousemove=function(event){
setPos(event);
}
smallWrap.onmouseout=function(){
smallWrap.removeChild(magnifier);
bigWrap.style.display=‘none‘;
}
function setPos(event){
var width=magnifier.clientWidth;
var height=magnifier.clientHeight;
var pos=getPosInElem(event,smallWrap);
var left=pos.x-width/2;
var top=pos.y-height/2;
if(left<0){left=0;}
if(left+width>swWidth){left=swWidth-width;}
if(top<0){top=0;}
if(top+height>swHeight){top=swHeight-height;}
magnifier.style.left=left+‘px‘;
magnifier.style.top=top+‘px‘;
bigWrap.style.display=‘block‘;
bigWrap.style.backgroundPosition=-left*ratio+‘px‘+‘ ‘+-top*ratio+‘px‘;
console.log(left+‘--‘+top);
}
function getPosInElem(event,elem){
return {
x:event.clientX-elem.getBoundingClientRect().left,
y:event.clientY-elem.getBoundingClientRect().top
}
}
原文:http://www.cnblogs.com/like-dream/p/7641872.html