效果图如下:
需求:鼠标放到小盒子上,让大盒子里面的图片和我们同步等比例移动
技术点:onmouseenter==onmouseover 第一个不冒泡
技术点:onmouseleave==onmouseout 第一个不冒泡
步骤:
1.鼠标放上去显示盒子,移开隐藏盒子
2.老三步和新五步(灰盒子跟随移动)
3.右侧的大图片,等比例移动
代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>放大镜</title> <style type="text/css"> *{ padding: 0; margin: 0; } .box{ width: 350px; height: 350px; margin: 100px; border: 1px solid red; position: relative; } .big{ width: 400px; height: 400px; position: absolute; top: 0; left: 360px; border: 1px solid blue; overflow: hidden; display: none; } .mask{ width: 175px; height: 175px; cursor: move; background-color: #DFD9F5; position: absolute; top: 0; left: 0; display: none; opacity: 0.5; } .small{ position: relative; border: 1px solid #22B14C; } </style> </head> <body> <div class="box"> <div class="small"> <img src="../images/001.jpg"/> <div class="mask"> </div><!--mask结束--> </div><!--small结束--> <div class="big"> <img src="../images/0001.jpg"/> </div> </div><!--box--> <script> //需求:鼠标放到小盒子上,让大盒子里面的图片和我们同步等比例移动 //技术点:onmouseenter==onmouseover 第一个不冒泡 //技术点:onmouseleave==onmouseout 第一个不冒泡 //步骤: //1.鼠标放上去显示盒子,移开隐藏盒子 //2.老三步和新五步(灰盒子跟随移动) //3.右侧的大图片,等比例移动 // //0.获取相关元素和相关事件源 var box= document.getElementsByClassName("box")[0]; var small = box.firstChild || box.firstElementChild; var mask = small.children[1]; var big = box.children[1]; var bigImg = big.children[0]; //1.鼠标放上去显示盒子,移开隐藏盒子 small.onmouseenter = function (){ big.style.display = "block"; mask.style.display = "block"; } small.onmouseleave = function (){ big.style.display = "none"; mask.style.display = "none"; } //2.老三步和新五步(灰盒子跟着鼠标移动) small.ommousemove = function(event){ event = event || window.event; var pagex = event.pageX || scroll().left+event.clientX; var pagey = event.pageY || scroll(). top+ event.clientY; //让鼠标处于遮罩的中间位置 var divx = pagex - small.offsetLeft - mask.offsetWidth/2; var divy = pagey - small.offsetTop - mask.offsetHeight/2; //约束盒子的值 if(divx<0){ divx =0; } if(divx>small.offsetWidth-mask.offsetWidth){ divx = small.offsetWidth - mask.offsetWidth; } if(divy<0){ divy=0; } if(divy>small.offsetWidth-mask.offsetWidth){ divy = small.offsetWidth-mask.offsetWidth; } mask.style.left = divx +"px"; mask.style.top = divy +"px"; //3.右侧的大图片,等比例移动 //求比例,让大图片等比例移动,大图片走的距离/mask走的距离 = 大图片/小图片 var bili = bigImg.offsetWidth/small.offsetWidth; var divxx = bili * divx; var divyy = bili * divy; bigImg.style.marginTop = -divxx +"px"; bigImg.style.marginLeft = -divyy+"px"; } </script> </body> </html>