js放大镜特效

js原生放大镜

body体里的代码

<div class="left">  //左边的大div
		<img src="./images/dali.jpg" width="100%" height="100%">
		<div class="mask"></div>  //放大镜的小块
	</div>
	<div class="right"> //右边的大div
		<img src="./images/dali.jpg">
	</div>

css样式代码

		//给左右两个div设置样式
.left, .right{
			width: 340px;
			height: 500px;
			border:1px solid red;
			float:left;
			margin-right:70px;
			position: relative;
		}
		
		//让右边的图片超出隐藏
		//最开始默认不显示,当鼠标进入才让他显示
		.right { 
			overflow: hidden;  
			display: none;
		}
		
		//放大镜的样式
		//默认不显示,鼠标进入显示
		.mask {
			width: 50px;
			height: 50px;
			background-color: rgba(0,0,255,0.5);
			position: absolute;
			left:0px;
			top:0px;
			display: none;
		}

一定要给放大镜设置定位属性,放大镜的移动原理就是利用,定位后修改他的top和left的值。

js代码

window.onload = function(){   //等页面加载完在执行js代码,防止图片没有加载好获取不到值
			// 获取元素节点
			let leftDiv = document.querySelector('.left')
			let mask    = document.querySelector('.mask')
			let rightDiv = document.querySelector('.right')
			let bigImg  = document.querySelector('.right img')

			// 2.小色块跟随鼠标移动
			leftDiv.onmousemove = function(e){
				let x = 0
				let y = 0
				if (e.target == mask) {
					x = e.offsetX + mask.offsetLeft
					y = e.offsetY + mask.offsetTop
				} else {
					x = e.offsetX
					y = e.offsetY
				}
				
				// 让鼠标显示在色块中心
				x = x - mask.offsetWidth/2
				y = y - mask.offsetHeight/2

				// 防止坐标超出边界
				let maxLeft = leftDiv.offsetWidth - mask.offsetWidth
				if (x < 0) {
					x = 0
				} else if (x > maxLeft) {
					x = maxLeft
				}
				let maxTop = leftDiv.offsetHeight - mask.offsetHeight
				if (y < 0) {
					y = 0
				} else if (y > maxTop) {
					y = maxTop
				}

				mask.style.left = x + 'px'
				mask.style.top  = y + 'px'

				// 左边横向移动的百分比
				let perX = - x / leftDiv.offsetWidth * 100 + '%'

				// 左边坚向移动的百分比
				let perY = - y / leftDiv.offsetHeight * 100 + '%'

				// console.log(perX,'----',perY)

				bigImg.style.transform = `translate(${perX},${perY})`
			}

			// 3.鼠标移入和移出
			leftDiv.onmouseenter = function(){
				mask.style.display = 'block'
				rightDiv.style.display = 'block'

				// 1.计算小色块尺寸
				let w = leftDiv.offsetWidth * rightDiv.offsetWidth / bigImg.offsetWidth
				let h = leftDiv.offsetHeight * rightDiv.offsetHeight / bigImg.offsetHeight
				mask.style.width = w + 'px'
				mask.style.height = h + 'px'
			}
			leftDiv.onmouseleave = function(){
				mask.style.display = 'none'
				rightDiv.style.display = 'none'
			}
		}
  • 13
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 17
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值