检查鼠标是否在元素的边界内 [英] Check if mouse is within element's bounds

查看:119
本文介绍了检查鼠标是否在元素的边界内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在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; //一个全局查找
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 / top坐标相对于文档)是真的做得很好,非常好的测试。你可以写自己的,但是,总计offsetLeft和offsetTop到文档。对于这个问题,你也可以用$替换$ .mousemove():

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

最后一件事:如果你回流页面,你需要再次调用store_boundary p>

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.

这篇关于检查鼠标是否在元素的边界内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆