放大镜效果

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>放大镜2</title>

<style type="text/css">
*{ margin:0; padding:0;}
.wrap{width:150px; margin:20px; position:relative;}
.wrap img{ width:100%; display:block;}
</style>
</head>
<body>
<div class="wrap">
    <img src="02.jpg" />
</div>
<div class="wrap">
    <img src="01.jpg" />
</div>
</body>
</html>

<script type="text/javascript">
var aDiv=document.getElementsByClassName("wrap");
for(var i=0;i<aDiv.length;i++){
    fang(aDiv[i])
}


function fang(obj){
    var o=obj;
    var oimg=o.getElementsByTagName("img")[0];
    var oDiv=document.createElement("div");
    oDiv.style.position="absolute";
    oDiv.style.top=o.offsetTop+"px";
    oDiv.style.left=o.offsetLeft+o.offsetWidth+5+"px";
    oDiv.style.height=o.offsetHeight+"px";
    oDiv.style.width=o.offsetWidth+"px";
    oDiv.style.overflow="hidden";
    oDiv.style.display="none";
    oDiv.innerHTML=o.innerHTML;
    
    document.body.appendChild(oDiv);
    
    
    var oDivIn=document.createElement("div");
    oDivIn.style.opacity=0.5;
    oDivIn.style.width=Math.ceil(o.offsetWidth/3)+"px";
    oDivIn.style.height=Math.ceil(o.offsetHeight/3)+"px";
    oDivIn.style.backgroundColor="#fff";
    oDivIn.style.position="absolute";
    oDivIn.style.left=0;
    oDivIn.style.top=0;
    
    o.appendChild(oDivIn);
    
o.onmouseover=function(e){
    var e=e||event;
    oDiv.style.display="block";
    oDivIn.style.left=e.clientX-o.offsetLeft-Math.ceil(oDivIn.offsetWidth/2)+"px";
    oDivIn.style.top=e.clientY-o.offsetTop-Math.ceil(oDivIn.offsetHeight/2)+"px";
    o.onmousemove=function(e){
        var e=e||event;
        var l=e.clientX-o.offsetLeft-Math.ceil(oDivIn.offsetWidth/2);
        var t=e.clientY-o.offsetTop-Math.ceil(oDivIn.offsetHeight/2);
        
        if(l<0){l=0}
        if(t<0){t=0}
        
        if(l>o.offsetWidth-oDivIn.offsetWidth){
            l=o.offsetWidth-oDivIn.offsetWidth;    
        }
        
        if(t>o.offsetHeight-oDivIn.offsetHeight){
            t=o.offsetHeight-oDivIn.offsetHeight;    
        }
        
        oDivIn.style.left=l+"px";
        oDivIn.style.top=t+"px";
        
        var Img=oDiv.getElementsByTagName("img")[0];
        
        Img.style.marginTop=-t*4+"px"
        Img.style.marginLeft=-l*4+"px"
        
    o.onmouseout=function(){
        oDiv.style.display="none";
        o.onmousemove=null;
        o.onmouseout=null;
    }
    }
}
}
</script>

公司好就是好,没有那么多事,其实这个效果是有问题的,就是不能出滚动条,哈哈,另外我也没有做兼容性处理,打击伸手党

原文地址:https://www.cnblogs.com/busicu/p/3747015.html