Tôi đã viết một câu trả lời tương tự như của bobince, nhưng anh ấy đã đến đó trước tôi. Tôi thích cách đó, nhưng phiên bản của anh ấy có một số tầng (mặc dù nó vẫn là một câu trả lời rất hay).
Tôi đoán rằng những gì bạn muốn là một lưới HTML ít hơn (có nghĩa là, không có đánh dấu như một bảng), mà bobince cung cấp một giải pháp cho. Trong trường hợp đó, mã có thể được tối ưu hóa đáng kể cho khả năng tương thích trình duyệt chéo, khả năng đọc, lỗi và tốc độ.
Vì vậy, tôi đề nghị các mã nên được nhiều như thế này:
#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]);;
}
};
Các mouseCoordinate() chức năng là một phiên bản luộc xuống hai chức năng:
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);
}
};
Tôi thực sự thích ý tưởng của dự án của bạn, có lẽ tôi sẽ làm một cái gì đó tương tự bản thân mình: D
Nguồn
2010-04-26 18:42:51
+1 cho hình ảnh :) – Jeriko