南宁小程序开发团队:http://www.zkelm.com
今天的课程是,用javascript实现淘宝的放大镜查看图片效果,移动鼠标过去的时候,图片会展示响应的位置
实现这个主要有1个难点,我做简单的介绍
1.就是阴影移动的最大距离, 和 大图片移动的最大距离比例
阴影移动最大距离/大图片移动最大距离=阴影移动left/大图片移动left
以上公式很重要, 明白了,这个 就可以很容易写出来 为了方便理解,我画了一个图
详细代码如下,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>移动放大镜</title>
<style type="text/css">
.box{
width:850px;
height:650px;
border: 1px solid #ccc;
display: flex;
}
.small{
width: 300px;
height: 300px;
border: 1px solid #aaa;
display: flex;
flex-direction: row;
justify-content: center;
position: relative;
}
.big{
width:500px;
height:500px;
border:1px solid #ccc;
overflow: hidden;
display: none;
position: relative;
}
.big img{
position: absolute;
top:0;
left:0;
}
.scan{
width:180px;
height: 180px;
background-color: yellow;
position: absolute;
opacity: 0.5;
cursor:move;
border: 1px solid #ccc;
display: none;
}
</style>
</head>
<body>
<div class="box">
<div class="small">
<img src="./images/iphone4-small.jpg"/>
<div class="scan"></div>
</div>
<div class="big"><img src="./images/iphone4_max.jpg"/></div>
</div>
</body>
<script type="text/javascript">
window.onload=function(){
var smallbox=document.querySelector(".small");
var scan=document.querySelector(".scan");
var bigbox=document.querySelector(".big");
smallbox.addEventListener("mouseover",function(){
scan.style.display="block";
bigbox.style.display="block";
})
smallbox.addEventListener("mouseout",function(){
scan.style.display="none";
bigbox.style.display="none";
})
smallbox.addEventListener("mousemove",function(e){
var left=e.pageX-smallbox.offsetLeft-(scan.offsetWidth/2);
var top=e.pageY-smallbox.offsetTop-(scan.offsetHeight/2)
if(left<=0 ){
left=0;
}else if(left+scan.offsetWidth>=smallbox.offsetWidth){
left=smallbox.offsetHeight-scan.offsetHeight;
}
if(top<=0){
top=0;
}else if(top+scan.offsetHeight>=smallbox.offsetHeight){
top=smallbox.offsetWidth-scan.offsetWidth;
}
scan.style.left=left+"px";
scan.style.top=top+"px";
var bigimg=document.querySelector(".big img");
bigimgoffsetx=(bigbox.offsetWidth-bigimg.offsetWidth)/2;
console.log(bigimgoffsetx);
bigimg.style.left=120-left+"px";
bigimg.style.top=-2.0*top+"px";
})
}
</script>
</html>
教程到这里了,有什么不懂的欢迎加我一起探讨,
南宁企业oa定制:www.zkelm.com