需求
1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着息标的移动而移动:
2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
原理
主要就是获取鼠标数据,取得鼠标移动数值,移入黄色框和大图显示,移出则不显示。
利用this取值,鼠标左右给值。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
margin: 0;
padding: 0;
}
.top{
height: 150px;
background-color: black;
color: white;
font-size: 50px;
text-align: center;
line-height: 150px;
margin-bottom: 100px;
}
#box{
height: 400px;
width: 700px;
float: left;
position: relative;
}
#box img{
display: inline-block;
height: 400px;
width: 700px;
}
#box2{
width: 450px;
height: 450px;
overflow: hidden;
float: left;
position: relative;
}
#sm{
width: 180px;
height: 180px;
background-color: yellow;
opacity: 0.3;
position: absolute;
top: 0;
left: 0;
}
#photo{
position: absolute;
top: 0;
left: 0;
}
.active{display: inline-block;}
.end{display: none;}
</style>
<title>Document</title>
</head>
<body>
<div class="top">JS放大镜</div>
<div id="box">
<img src="./b.jpg" alt="">
<div class="end" id="sm"></div>
</div>
<div id="box2" class="end">
<img src="./b.jpg" alt="ph" id="photo">
</div>
<script>
var box = document.getElementById("box");
var box2 = document.getElementById("box2");
var sm = document.getElementById("sm");
var photo = document.getElementById("photo");
var cleft=0,ctop=0,x=0,y=0,m=0,n=0;
box.onmouseenter = function(){
box2.className="active";
sm.className="active";
}
box.onmouseleave = function(){
box2.className="end";
sm.className="end";
}
sm.onmousedown = function(e){
x =e.clientX-this.offsetLeft;
y =e.clientY-this.offsetTop;
document.onmousemove = function(e){
cleft =e.clientX-x;
ctop =e.clientY-y;
if(cleft<=0){
cleft=0;
}
if(cleft>=box.offsetWidth - sm.offsetWidth){
cleft =box.offsetWidth - sm.offsetWidth;
}
if(ctop<=0){
ctop=0;
}
if(ctop>=box.offsetHeight - sm.offsetHeight){
ctop = box.offsetHeight-sm.offsetHeight;
}
m = -(parseInt(((photo.offsetWidth+x)/box2.offsetWidth)*cleft));
n = -(parseInt(((photo.offsetHeight+y)/box2.offsetHeight)*ctop));
sm.style.left = cleft+"px";
photo.style.left = m+"px";
sm.style.top = ctop+"px";
photo.style.top = n +'px';
}.bind(this)
document.onmouseup = function(e){
document.onmousemove = "null";
document.onmouseup = "null";
}
}
</script>
</body>
</html>
效果