私は最初、ボビンスと同様の回答を書いていましたが、彼は私より先にそこにたどり着きました。私はその方法が好きですが、彼のバージョンにはいくつかのフロアがあります(それでも非常に良い答えですが).
あなたが望むのは、ボビンスがソリューションを提供する HTML レス グリッド (つまり、テーブルのようなマークアップなし) だと思います。その場合、コードはブラウザ間の互換性、読みやすさ、エラー、および速度のために大幅に最適化される場合があります。
したがって、コードは次のようにすることをお勧めします。
#canvas { position: relative; width: 100px; height: 100px; border: solid red 1px; }
#nearest { position: absolute; width: 10px; height: 10px; background: yellow; }
<div id="canvas"><div id="nearest"></div></div>
var
canvasOffset = $("div#canvas").offset(),
// Assuming that the space between the points is 10 pixels. Correct this if necessary.
cellSpacing = 10;
$("div#canvas").mousemove(function(event) {
event = event || window.event;
$("div#nearest").css({
top: Math.round((mouseCoordinate(event, "X") - canvasOffset.left) / cellSpacing) * cellSpacing + "px",
left: Math.round((mouseCoordinate(event, "Y") - canvasOffset.top) / cellSpacing) * cellSpacing + "px"
});
});
// Returns the one half of the current mouse coordinates relative to the browser window.
// Assumes the axis parameter to be uppercase: Either "X" or "Y".
function mouseCoordinate(event, axis) {
var property = (axis == "X") ? "scrollLeft" : "scrollTop";
if (event.pageX) {
return event["page"+axis];
} else {
return event["client"+axis] + (document.documentElement[property] ? document.documentElement[property] : document.body[property]);;
}
};
mouseCoordinate() 関数は、これら 2 つの関数の煮詰めたバージョンです。
function mouseAxisX(event) {
if (event.pageX) {
return event.pageX;
} else if (event.clientX) {
return event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
}
};
function mouseAxisY(event) {
if (event.pageY) {
return event.pageY;
} else if (event.clientY) {
return event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
};
私はあなたのプロジェクトのアイデアが本当に好きです, おそらく私は自分自身に似たものを作るでしょう:D