放大镜效果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{padding: 0;margin: 0}
#div1{width: 180px;height: 180px;position: relative;overflow: hidden;margin: 100px}
#div1 span{width: 100px;height: 100px;background:yellow;position: absolute;top: 0;left: 0;opacity: 0.5;filter: alpga(opacity=50);display: none}
#div2{ width:500px; height:500px; position:absolute; left:400px; top:200px; overflow:hidden;display: none}
#div2 img{ position:absolute; left:0; top:0;}
</style>
</head>
<body>
<div id="div1">
<img src="images/b2.jpg" alt="">
<span></span>
</div>
<div id="div2">
<img src="images/b1.jpg">
</div>
<script>
var oDiv =document.querySelector("div");
var oSpan=document.querySelector("span");
var oDiv2 = document.getElementById('div2');
     var img2 = oDiv2.getElementsByTagName('img')[0];
oDiv.onmouseenter=function(){
oSpan.style.display='block';
oDiv2.style.display="block"
};
oDiv.onmouseleave=function(){
oSpan.style.display='none';
oDiv2.style.display="none"
};
oDiv.onmousemove=function(ev){
var ev=ev||window.event;
var L =ev.clientX -oDiv.offsetLeft-oSpan.offsetWidth/2;
var T =ev.clientY -oDiv.offsetTop-oSpan.offsetHeight/2;
if(L<0){
L=0;
}else if(L>oDiv.offsetWidth-oSpan.offsetWidth){
L=oDiv.offsetWidth-oSpan.offsetWidth;
console.log(L)
};
if(T<0){
T=0
}else if(T>oDiv.offsetHeight-oSpan.offsetHeight){
T=oDiv.offsetHeight-oSpan.offsetHeight
T = oDiv.offsetHeight - oSpan.offsetHeight;
}
oSpan.style.left=L+'px';
oSpan.style.top=T+'px';
var scaleX =L/(oDiv.offsetWidth -oSpan.offsetWidth);
var scaleY =T/(oDiv.offsetHeight -oSpan.offsetHeight);
img2.style.left=scaleX*(oDiv2.offsetWidth -img2.offsetWidth) +'px';
img2.style.top=scaleY*(oDiv2.offsetHeight -img2.offsetHeight) +'px';
};
//用比例控制大图的活动范围
//onmouseenter onmouseleave 不会冒泡,另外也可以使用遮罩防止事件冒泡
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/hilxj/p/11251627.html