Al principio estaba escribiendo una respuesta similar a la de bobince, pero llegó antes que yo. Me gusta esa forma de hacerlo, pero su versión tiene algunos pisos (aunque sigue siendo una muy buena respuesta).
Supongo que lo que quiere es una cuadrícula sin HTML (es decir, sin marcado como una tabla), para lo que bobince proporciona una solución. En ese caso, el código puede optimizarse significativamente para compatibilidad, legibilidad, errores y velocidad entre navegadores.
Por lo tanto, sugieren que el código debe ser de la misma familia:
#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]);;
}
};
La función mouseCoordinate() es una versión reducía de estas dos funciones:
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);
}
};
me gusta mucho la idea de su proyecto, quizás haré algo similar yo mismo: D
+1 para la imagen :) – Jeriko