原生JS实现简单放大镜效果

【前言】

    本文介绍下原生JS实现简单图片放大镜效果

 

【主体】

   时间问题,直接上源码

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>放大镜</title>
	<style type="text/css">
		/*代码初始化*/
		*{
			margin: 0;
			padding: 0;
		}
		/*代码主体*/
		.small_box{
			width: 300px;
			height: 300px;
			border: 1px solid black;
			float: left;
			cursor: move;
			margin-left:100px;
			margin-top:100px;
			position: relative;
		}
		.small_box img{
			width: 300px;
			height: 300px;
		}
		.fdj{
			width: 50%;
			height: 50%;
			background-color:rgba(200,200,1,0.6);
    		position:absolute;
		    left:0px;
		    top:0px;
		    display:none;
		}
		.big_box{
			width:300px;
		    height:300px;
		    /*border:1px solid black;*/
		    overflow:hidden;
		    box-sizing: border-box;
		    float:left;
		    margin-top:100px;
		    position:relative;
		    display:none;
		}
		.big_box img{
			position: absolute;
			width: 200%;
			height: 200%;
		}
		.small_box .active,.active{
			display: block;
		}
	</style>
</head>
<body>
	<div class="small_box">
		<img src="01.jpg" alt="汪星人">
		<div class="fdj"></div>
	</div>
	<div class="big_box">
		<img class="big_img" src="01.jpg" alt="汪星人">
	</div>
	<script type="text/javascript">
		 var small_box = document.getElementsByClassName("small_box")[0];//小盒子
		 var fdj = document.getElementsByClassName("fdj")[0];//小盒子中的黄色区域
		 var big_box = document.getElementsByClassName("big_box")[0];//大盒子
		 var big_img = document.getElementsByClassName("big_img")[0];//放大的图片
		 //鼠标进入小盒子区域内,显示黄色区域和大盒子
		 small_box.onmouseenter = function(){
		 	fdj.className = "fdj active";
		 	big_box.className = "big_box active";
		 }
		 //鼠标离开小盒子区域,不显示黄色区域和大盒子
		 small_box.onmouseleave = function(){
		 	fdj.className = "fdj";
		 	big_box.className = "big_box";
		 }
		 //鼠标在小盒子内移动
		 small_box.onmousemove = function(event){
		 	// console.log(event.clientX);//clientX 设置或获取鼠标指针位置相对于窗口客户区域的 x 坐标
		 	// console.log(this.offsetLeft);//当前元素顶部相对于指定定位属性祖先元素左侧的偏移量
		 	// console.log(fdj.offsetWidth/2);//小黄盒子宽度一半
		 	var x = event.clientX-this.offsetLeft-fdj.offsetWidth/2;//事件对象在小盒子内的横向偏移量
		 	var y = event.clientY-this.offsetTop-fdj.offsetHeight/2;//竖向偏移量
		 	
		 	if(x<0){x=0};//当左偏移出小盒子时,设为0
		 	if(y<0){y=0};//当上偏移出小盒子时,设为0

		 	if(x>this.offsetWidth-fdj.offsetWidth){
		 		 x = this.offsetWidth-fdj.offsetWidth;//当右偏移出小盒子时,设为小盒子的宽度-黄色放大区域宽度
		 	}
		 	if(y>this.offsetHeight-fdj.offsetHeight){
		 		y = this.offsetHeight-fdj.offsetHeight;//当下偏移出小盒子时,设为小盒子的高度-黄色放大区域高度
		 	}

		 	fdj.style.left = x + "px";//黄色放大区域距离小盒子左偏距
		 	fdj.style.top = y + "px";//黄色放大区域距离小盒子上偏距

		 	big_img.style.left = -x*2 + "px";//放大图片移动方向相反,偏移距离加倍
		 	big_img.style.top = -y*2 + "px";
		 }
	</script>
</body>
</html>

 

 

.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值