我最初正在寫一個類似於bobince的答案,但他在我之前到達了那裏。我喜歡這樣做,但他的版本已經有了一些層次(儘管它仍然是一個非常好的答案)。
我認爲你想要的是一個無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 2010-04-26 10:55:06