很多电商网站比如:京东、天猫、淘宝都有放大镜效果,每当看到心仪的物品时,鼠标移入图片时,便呈现出放大的效果。在没有去理解分析它的原理时,感觉非常的神奇,当真正地去接触,也是非常好理解。如下图展示所见:
逻辑分析:
1. 有2个图片(大图、小图),图片之间都有很好尺寸比例
2. 鼠标移入小图这里事件采用onmousemove事件,移入后显示阴影部分以及右侧大图
3. 当鼠标移出则隐藏阴影部分以及右侧大图
4. 鼠标在小图移动,阴影部分跟随采用clientX和clientY的位移
5. 鼠标在小图部分左边移动,大图向右,刚好相反并且*其比例尺寸就是大图要移动的位置
代码实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
*{margin:0;padding: 0}
#box{
width:1200px;
height: 700px;
border:1px solid #ccc;
margin:150px;
}
#min{
float:left;
width:400px;
height: 400px;
position: relative;
}
b{
position: absolute;
left:0;
top:0;
width:200px;
height: 200px;
background: blue;
opacity: 0.5;
display: none;
}
#max{
float:right;
width:400px;
height: 400px;
overflow: hidden;
display: none;
position: relative;
}
#imgs{
position: absolute;
left:0;
top:0;
}
</style>
<body style="height: 2000px">
<div id="box">
<div id="min"><img src="imgs/min.jpg" alt=""><b></b></div>
<div id="max"><img src="imgs/max.jpg" alt="" id="imgs"></div>
</div>
<script type="text/javascript">
//1》鼠标移入到min这个盒子中,显示出来 放大图片的盒子和小阴影部分
//2》阴影跟随鼠标移动====》
var min = document.getElementById("min"),
max = document.getElementById("max"),
b = document.getElementsByTagName("b")[0],
imgs = document.getElementById("imgs");
min.onmousemove = function(e){
b.style.display = "block";
max.style.display = "block";
var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
var x = e.clientX+scrollLeft-min.offsetLeft- b.offsetWidth/2;
var y = e.clientY+scrollTop-min.offsetTop - b.offsetHeight/2;
if(x<0){
x=0;
}else if(x>min.offsetWidth-b.offsetWidth){
x=min.offsetWidth-b.offsetWidth;
}
if(y<0){
y=0;
}else if(y>min.offsetHeight-b.offsetHeight){
y=min.offsetHeight-b.offsetHeight;
}
b.style.left =x+"px";
b.style.top =y+"px";
imgs.style.left = -2*x+"px";
imgs.style.top = -2*y+"px";
}
min.onmouseout = function(){
b.style.display = "none";
max.style.display = "none";
}
</script>
</body>
</html>
原文:https://www.3mooc.com/front/articleinfo/148
网友评论