有沒有在javascript中檢查鼠標位置是否位於元素邊界內的方法?檢查鼠標是否在元素的邊界內
有沒有可以提供的功能或快速的方法?
if (document.mouse.x > ele.offsetLeft && document.mouse.x < ele.offsetRight ...check y bounds)
{
return true;
}
else return false;
有沒有在javascript中檢查鼠標位置是否位於元素邊界內的方法?檢查鼠標是否在元素的邊界內
有沒有可以提供的功能或快速的方法?
if (document.mouse.x > ele.offsetLeft && document.mouse.x < ele.offsetRight ...check y bounds)
{
return true;
}
else return false;
您可以存儲邊界座標和鼠標座標。這可以讓你隨時檢查它。
var coords = [0,0];
$(document).mousemove(function(e){
var C = coords; // one global lookup
C[0] = e.pageX;
C[1] = e.pageY;
});
var box_area = {x1:0, y1:0, x2:0, y2:0};
var box = $('#box');
function store_boundary() {
var B = box, O = B.offset();
box_area = {
x1: O.left,
y1: O.top,
x2: O.left + B.width(),
y2: O.top + B.height()
};
}
store_boundary();
function is_mouse_in_area() {
var C = coords, B = box_area;
if (C[0] >= B.x1 && C[0] <= B.x2) {
if (C[1] >= B.y1 && C[1] <= B.y2) {
return true;
}
}
return false;
};
我想給你不jQuery的答案,但我認爲.offset()(左/頂部座標相對於文檔)真的做得很好,非常行之有效的。但是,您可以編寫自己的文件,總計offsetLeft和offset爲文檔。對於這個問題,你也可以替換$ .mousemove()有:
document.addEventListener('mousemove',function(e){ ... },false);
最後一件事:如果你迴流的頁面,你需要()再次調用store_boundary。
var t = $("#element"); var mouseX = event.clientX + document.body.scrollLeft; var mouseY = event.clientY + document.body.scrollTop; if (mouseX >= t.offset().left && mouseX <= t.offset().left + t.width() && mouseY >= t.offset().top && mouseY <= t.offset().top + t.height()) { return true; }
'onMouseOver'屬性如何? –