南宁小程序开发,挑战百日学习计划第44天(javascript实现图片放大镜效果)

南宁小程序开发团队:http://www.zkelm.com

今天的课程是,用javascript实现淘宝的放大镜查看图片效果,移动鼠标过去的时候,图片会展示响应的位置
南宁小程序开发:www.zkelm.com

实现这个主要有1个难点,我做简单的介绍
1.就是阴影移动的最大距离, 和 大图片移动的最大距离比例
阴影移动最大距离/大图片移动最大距离=阴影移动left/大图片移动left
以上公式很重要, 明白了,这个 就可以很容易写出来 为了方便理解,我画了一个图

南宁小程序开发:www.zkelm.com

详细代码如下,

<!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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值