나는 처음에는 보빈스와 비슷한 대답을 쓰고 있었지만, 그는 내 앞에 거기에갔습니다. 나는 그 일을하는 방식을 좋아하지만, 그의 버전은 약간의지면을 가지고있다. (여전히 아주 좋은 대답이다.)
내가 원하는 것은 보빈이 솔루션을 제공하는 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() 함수는 두 함수의 다운 삶은 버전 :
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
+1 그림 : – Jeriko