检查鼠标是否在元素的范围内

时间:2011-09-13 05:47:10

标签: javascript html css

javascript中是否有办法检查鼠标位置当前是否位于元素的边界内?

是否有可以建议的功能或快速的方法?

if ( document.mouse.x > ele.offsetLeft && document.mouse.x < ele.offsetRight ...check y bounds)
{
  return true;
}
else return false;

2 个答案:

答案 0 :(得分:1)

您可以存储边界坐标和鼠标坐标。这可以让你随时检查它。

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和offsetTop到文档。就此而言,您还可以将$ .mousemove()替换为:

document.addEventListener('mousemove',function(e){ ... },false);

最后一件事:如果您重排页面,则需要再次调用store_boundary()。

答案 1 :(得分:0)

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; }

相关问题