JS实现放大镜效果

html布局

在这里插入图片描述

css效果

<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}

			#fdj {
				width: 418px;
				height: 418px;
				position: relative;
			}

			.small {
				background: red;
				width: 418px;
				height: 418px;
			}

			.small img {
				width: 418px;
				height: 418px;
			}

			.big {
				position: absolute;
				height: 418px;
				width: 418px;
				left: 450px;
				top: 0;
				overflow: hidden;
				display: none;
			}

			.big-img {
				position: absolute;
				left: 0;
				top: 0;
			}

			.mask {
				width: 200px;
				height: 200px;
				background: rgba(255, 255, 0, 0.3);
				position: absolute;
				left: 0px;
				top: 0px;
				display: none;
			}
		</style>

JS效果实现

<script type="text/javascript">
		
		//封装class
		class Fdj {
			constructor(sel) {
				this.el = document.querySelector(sel)
				this.mask = this.el.querySelector('.mask')
				this.small = this.el.querySelector('.small')
				this.big = this.el.querySelector('.big')
				this.bigImg = this.el.querySelector('.big-img')

				//获取big的宽
				let bigImgHeight = parseInt(getComputedStyle(this.big).height) * this.small.offsetHeight / parseInt(
					getComputedStyle(this.mask).height)
				
				this.bigImg.style.height = bigImgHeight + 'px';
				
				//鼠标移入显示
				this.el.onmouseenter = () => {
					this.mask.style.display = 'block';
					this.big.style.display = 'block';
				}

				//鼠标离开隐藏
				this.el.onmouseleave = () => {
					this.mask.style.display = 'none';
					this.big.style.display = 'none';
				}
				
				
				this.small.onmousemove = (evt) => {
					
					//获取鼠标坐标
					let x = evt.pageX - this.el.offsetLeft;
					let y = evt.pageY - this.el.offsetTop;
					
					//获取mask的位置信息
					let maskX = x - this.mask.offsetWidth / 2;
					let maskY = y - this.mask.offsetWidth / 2;
					

					//判断mask是否移出
					if (maskX <= 0) {
						maskX = 0;
					}
					if (maskX >= this.small.offsetWidth - this.mask.offsetWidth) {
						maskX = this.small.offsetWidth - this.mask.offsetWidth;
					}
					if (maskY >= this.small.offsetWidth - this.mask.offsetWidth) {
						maskY = this.small.offsetWidth - this.mask.offsetWidth;
					}
					if (maskY <= 0) {
						maskY = 0;
					}
					
					//mask的移动
					this.mask.style.left = maskX + 'px';
					this.mask.style.top = maskY + 'px';

					//大图的移动
					this.bigImg.style.left = -maskX * bigImgHeight / this.small.offsetHeight + 'px';
					this.bigImg.style.top = -maskY * bigImgHeight / this.small.offsetHeight + 'px';
				}
			}
		}
		
		//调用
		new Fdj('#fdj')
		
	</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值