商品放大镜
鼠标事件
移入:移入到left元素上,mask和right显示
遮罩跟随:鼠标到哪里我的遮罩就运动到哪里
宽高问题
遮罩的大小/小图的大小=大盒子的大小/大图的大小
样式
#box{ width: 200px; height: 200px; border: 3px solid black; position: relative; } #left{ width: 200px; height: 200px; border: 3px solid red; position: absolute; /* 让box和left重合 */ left: -3px; top: -3px; background: url(./img/1.jpg); background-size: 200px 200px; } #right{ width: 200px; height: 200px; border: 3px solid blue; position: absolute; left: 220px; top: -3px; background: url(./img/1.jpg) no-repeat; background-size: 400px 400px; display: none; } /* mask的大小需要遵循一定的比例 遮罩的大小/小图的大小=大盒子的大小/大图的大小 */ #mask{ width: 100px; height: 100px; background-color: rgba(255, 255, 0, 0.3); display: none; position: absolute; }
结构
<body> <div id="box"> <div id="left"> <div id="mask"></div> </div> <div id="right"></div> </div> </body>
js代码
/* 移入:移入到left元素上,mask和right显示 遮罩跟随:鼠标到哪里我的遮罩就运动到哪里 */ var oBox=document.querySelector('#box') var oLeft=oBox.children[0] var oRight=oBox.children[1] var oMask=oLeft.children[0] //移入移出的效果 oLeft.onmouseover=function(){ oMask.style.display='block' oRight.style.display='block' } oLeft.onmouseout=function(){ oMask.style.display='none' oRight.style.display='none' } //遮罩跟随:鼠标到哪里我的遮罩就运动到哪里(联想到天使飞,鼠标到哪儿,天使就飞到哪儿) oLeft.onmousemove=function(e){ let l=e.clientX-oBox.offsetLeft let t=e.clientY-oBox.offsetTop let ll=l-oMask.offsetWidth/2 let tt=t-oMask.offsetHeight/2 if(ll<0){ ll=0 } if(ll>=oLeft.clientWidth-oMask.offsetWidth){ ll=oLeft.clientWidth-oMask.offsetWidth } if(tt<0){ tt=0 } if(tt>=oLeft.clientHeight-oMask.offsetHeight){ tt=oLeft.clientHeight-oMask.offsetHeight } // ll和tt分别是遮罩层的运动的left和top,大图运动的应该是2倍 ll和tt oMask.style.left=ll+'px' oMask.style.top=tt+'px' oRight.style.backgroundPositionX=-2*ll+'px' oRight.style.backgroundPositionY=-2*tt+'px' } //x=200*200/400=100
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY