元素跟随鼠标在指定区域运动通常是用在商城图片的放大镜中,下面是完整的Demo:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>鼠标区域</title> <style type="text/css"> *{margin:0;padding:0;} .area{ width:400px; height:400px; margin:30px auto; background: #ccc; overflow: hidden; position: relative; } .hover{ border:1px dashed #000; width:100px; height:100px; background: rgba(0,0,0,0.25); position: absolute; display: none; cursor: move; } </style> </head> <body> <div id="area" class="area"> <div class="hover" id="hover"> </div> <script type="text/javascript"> var $box = document.getElementById("area"); var $hover = document.getElementById("hover"); var boxW=$box.offsetWidth, boxH=$box.offsetHeight, boxLeft=$box.offsetLeft, boxTop=$box.offsetTop; var startX,startY,hoverW,hoverH; $box.onmouseover=function(event){ var event=event||window.event; $hover.style.display="block"; hoverW=$hover.offsetWidth, hoverH=$hover.offsetHeight; var x = event.clientX; var y = event.clientY; $hover.style.left=(x-boxLeft-hoverW/2)+"px"; $hover.style.top=(y-boxTop-hoverH/2)+"px"; console.log(boxW+"<br/>"+hoverW) } $box.onmousemove=function(event){ var event=event||window.event; var x = event.clientX; var y = event.clientY; var resultX,resultY; if(x-boxLeft-50<0){ resultX=0; }else if(x-boxLeft-50>=boxW-hoverW){ resultX=boxW-hoverW; }else{ resultX=x-boxLeft-50; } if(y-boxTop-50<0){ resultY=0 }else if(y-boxTop-50>=boxH-hoverH){ resultY=boxH-hoverH; }else{ resultY=y-boxTop-50; } $hover.style.left=resultX+"px"; $hover.style.top=resultY+"px"; } $box.onmouseout = function(event) { var event=event||window.event; var x = event.clientX; var y = event.clientY; var divx1 = $box.offsetLeft; var divy1 = $box.offsetTop; var divx2 = $box.offsetLeft + $box.offsetWidth; var divy2 = $box.offsetTop + $box.offsetHeight; if (x < divx1 || x > divx2 || y < divy1 || y > divy2) { $hover.style.display="none"; } } </script> </body> </html>
主要是两个关键点:
1、获取鼠标当前位置,然后设置运动元素的当前位置为鼠标位置;
2、判断元素是否靠近父级元素的边界,设置临界值;