效果:
结构:
html:
<!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">
<link rel="stylesheet" href="max.css">
<title>放大镜</title>
</head>
<body>
<div class="box">
<img src="./img/hezi.jpg" alt="渺小一生" />
<div class="block"></div>
</div>
<div class="max">
<img class="bImg" src="./img/max.jpg" alt="max" />
</div>
<script>
/* onmouseenter
onmouseleave
onmousemove=function(ev){
ev,事件对象上存储有鼠标的位置信息
} */
var box = document.getElementsByClassName("box")[0];
var block = document.getElementsByClassName("block")[0];
var max = document.getElementsByClassName("max")[0];
var bImg = document.getElementsByClassName("bImg")[0];
box.addEventListener("mousemove",function(e){
var x = e.clientX;
var y = e.clientY;
// console.log(x,y)
var left = x-box.getBoundingClientRect().left-block.getBoundingClientRect().width/2;
var top = y-box.getBoundingClientRect().top-block.getBoundingClientRect().height/2;
if(left<=0){
left=0;
}
if(top<=0){
top=0;
}
if(left>=box.getBoundingClientRect().width-block.getBoundingClientRect().width){
left=box.getBoundingClientRect().width-block.getBoundingClientRect().width;
}
if(top>=box.getBoundingClientRect().height-block.getBoundingClientRect().height){
top=box.getBoundingClientRect().height-block.getBoundingClientRect().height;
}
block.style.left=left+"px";
block.style.top=top+"px";
bImg.style.left=-left*(bImg.getBoundingClientRect().width/block.getBoundingClientRect().width)+"px";
bImg.style.top=-top*(bImg.getBoundingClientRect().height/block.getBoundingClientRect().height)+"px";
})
box.onmouseenter = function(){
block.style.display="block";
max.style.display="block";
}
box.onmouseleave = function(){
block.style.display="none";
max.style.display="none";
}
</script>
</body>
</html>
css:
*{
margin: 0px;
padding: 0px;
}
.box{
margin: 50px;
width: 360px;
height: 360px;
background-color: white;
border: 1px solid #DFDFDF;
position: relative;
}
.max{
border: 1px solid #DFDFDF;
/* background-image: url(./img/max.jpg);
background-repeat: no-repeat; */
width: 500px;
height: 500px;
position: absolute;
left: 410px;
top: 50px;
display: none;
overflow: hidden;
}
.bImg{
position: absolute;
left: 0px;
top: 0px;
}
.block{
width: 240px;
height: 240px;
background-color: yellow;
opacity: 0.3;
border: 1px solid #DFDFDF;
position: absolute;
top: 0px;
left: 0px;
display: none;
cursor: move;
}