简体   繁体   English

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

[英]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? javascript中有没有一种方法可以检查鼠标当前是否位于元素范围内?

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. 我想给你一个没有jQuery的答案,但我认为.offset()(相对于文档的左/上坐标)确实做得很好并且经过了很好的测试。 You could write your own, however, that totals up offsetLeft and offsetTop up to document. 但是,您可以编写自己的文件,将offsetLeft和offsetTop总计为文档。 For that matter, you could also replace $.mousemove() with: 为此,您还可以将$ .mousemove()替换为:

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

One last thing: if you reflow the page, you need to call store_boundary() again. 最后一件事:如果要重排页面,则需要再次调用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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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