js电商的简单放大镜效果详解

j放大镜分享

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			#small-box{
				width: 200px;
				height: 200px;
				background-image: ur## 标题l(img/0.jpg);
				background-size: 200px 200px;
				position: absolute;
				left: 100px;
				top: 200px;
			}
			#big-box{
				width: 400px;
				height: 400px;
				background-image: url(img/0.jpg);
				background-size: 800px 800px;
				position: absolute;
				left: 400px;
				top: 200px;
				display: none;
				position: absolute;
			}
			#mask{
				height: 100px;
				width: 100px;
				opacity: 0.3;
				background-color: red;
				display: none;
				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="small-box">
			<div id="mask"></div>
		</div>
		<div id="big-box"></div>
	</body>
</html>
<script>
	class Magnifier{
		constructor(newSmallBox,newBigBox,newMask){
			this.smallBox=newSmallBox;
			this.bigBox=newBigBox;
			this.mask=newMask;
		}
		//添加鼠标移到
		onmouseover(){
			let that=this;
			this.smallBox.onmouseover=function(){
				that.bigBox.style.display="block";
				that.mask.style.display="block";
			}
		}
		//添加鼠标移开
		onmouseout(){
			let that=this;
			this.smallBox.onmouseout=function(){
				that.bigBox.style.display="none";
				that.mask.style.display="none";
			}
			}
//		//鼠标移动 拖拽效果
	    onmousemove(){
	    	let that =this;
	    	this.smallBox.onmousemove=function(evt){
	    		let e=evt||event;
	    		let left=e.pageX - this.offsetLeft - that.mask.offsetWidth/2;
	    		let top=e.pageY - this.offsetTop - that.mask.offsetHeight/2;
	    		//越界问题
	    		if(left<0){
	    			left=0;
	    		}
	    		let maxLeft=this.offsetWidth-that.mask.offsetWidth;
	    		if(left>maxLeft){
	    			left=maxLeft
	    		}
	    		if(top<0){
	    			top=0;
	    		}
	    		let maxTop=this.offsetHeight-that.mask.offsetHeight;
	    		if(top>maxTop){
	    			top=maxTop;
	    		}
	    		//公式 反向运动
	    		let x=left*that.bigBox.offsetWidth/that.mask.offsetWidth;
	    		let y=top*that.bigBox.offsetHeight/that.mask.offsetHeight;
	    		
	    		that.mask.style.left=left+ "px";
	    		that.mask.style.top=top+ "px"
	    		
	    		//水平垂直位置
	    		that.bigBox.style.backgroundPositionX=-x+"px";
	    		that.bigBox.style.backgroundPositionY=-y+"px";
	    	}
	    }

	}
	let osmallBox = document.getElementById("small-box");
	let omask = document.getElementById("mask");
	let oBigBox=document.getElementById("big-box")
	let mf= new Magnifier(osmallBox,oBigBox,omask);
	mf.onmouseover();
	mf.onmouseout();
	mf.onmousemove();
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值