### DIV捕捉到网格并按照鼠标

``````\$(document).mousemove(function(e) {
window.x = e.pageX;
window.y = e.pageY;
if(window.x % 9 === 0 ){
\$("div").css("left",window.x);
\$("div").css("top",window.y);
}
});
``````

#### 1 个答案:

<强>更新

``````\$(document).mousemove(function(e) {
demiSquareX = \$(".inner").width()/2;
demiSquareY = \$(".inner").height()/2;
windowX = e.pageX - \$(".outer").offset().left - demiSquareX ;
windowY = e.pageY - \$(".outer").offset().top - demiSquareY;
if(windowX<=0 || windowX >=(\$(".outer").width()-\$(".inner").width()) || windowY <=0 || windowY >= (\$(".outer").height()-\$(".inner").height())){
//out
}else{
if(windowX % 3 == 0 || windowY % 3 == 0){
\$(".inner").css("left",windowX);
\$(".inner").css("top",windowY);
}
}
});``````
``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer" style="border:3px solid black;width:300px;position:relative;height:300px;left:100px;top:50px">
<div class="inner" style="background:red;width:20px;height:20px;position:absolute"></div>
</div>``````