纯原生js实现实现放大镜特效
**先上效果图
接下来是html概览,因为要通过js去操作dom做特效需要在html里拿到id或class
js代码实现
window.addEventListener('load',function(){ var box=document.querySelector('.img'); var move=document.querySelector('.move'); var big=document.querySelector('.big'); //鼠标的进出去决定盒子的出现 box.addEventListener('mouseover',function(){ • move.style.display='block'; • big.style.display='block'; • box.addEventListener('mouseout',function(){ • move.style.display='none'; • big.style.display='none'; • }) }) //鼠标跟随 box.addEventListener('mousemove',function(e){//这里的e为event事件的缩写,用操作对象 //的回调来做形参 • var x=e.pageX-this.offsetLeft; • var y=e.pageY-this.offsetTop; • moveX=x-move.offsetWidth/2; • moveY=y-move.offsetHeight/2; • console.log(box.offsetWidth-move.offsetWidth); • //让move只能在盒子范围内移动 • if(moveX<=0){ • moveX=0; • }else if(moveX>=box.offsetWidth-move.offsetWidth){ • moveX=box.offsetWidth-move.offsetWidth; • } • if(moveY<=0){ • moveY=0; • }else if(moveY>=box.offsetHeight-move.offsetHeight){ • moveY=box.offsetHeight-move.offsetHeight; • } • move.style.left=moveX+'px'; • move.style.top=moveY+'px'; • movemax=box.offsetWidth-move.offsetWidth; • //大图的移动,按比例移动 • var b=document.querySelector('.b'); • var bMax=b.offsetWidth-big.offsetWidth; • console.log(bMax); • var bX=moveX*bMax/movemax; • var bY=moveY*bMax/movemax; //大图的移动方向应该与鼠标相反,所以是-bx,-by • b.style.marginLeft=(-bX+'px'); • b.style.marginTop=(-bY+'px'); }) })