简体   繁体   中英

Check if mouse is within element's bounds

Is there a way in javascript to check whether the mouse position currently lies within an element's bounds?

Is there a function you can suggest or a method thats quick?

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

You could store the boundary coordinates and the mouse coordinates. This would let you check it any time you want.

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

I would like to have given you an answer without jQuery, but I think .offset() (left/top coordinates relative to the document) is really well done and very well tested. You could write your own, however, that totals up offsetLeft and offsetTop up to document. For that matter, you could also replace $.mousemove() with:

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

One last thing: if you reflow the page, you need to call store_boundary() again.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM