需要在javascript中捕获鼠标位置

时间:2011-12-02 06:24:50

标签: javascript ajax events dom

如何使用javascript和画布捕捉鼠标的位置?

当我转到此页面时:http://billmill.org/static/canvastutorial/mouse.html

他们表明了这一点:

function init_mouse() {
  canvasMinX = $("#canvas").offset().left;
  canvasMaxX = canvasMinX + WIDTH;
}

function onMouseMove(evt) {
  if (evt.pageX > canvasMinX && evt.pageX < canvasMaxX) { //how can you access the canvasMinX when its out of scope?
//also, what is pageX? is it the coordinate of the mouse? if not, how do i get it?
    paddlex = evt.pageX - canvasMinX;
  }
}

$(document).mousemove(onMouseMove);

最后,我需要在鼠标点击时发生这种情况。所以我这样做:

$(document).mouseclick(onMouseClick)

是吗?

2 个答案:

答案 0 :(得分:1)

这是如何使用JS实现它的完美解释:JavaScript Capture Mouse X-Y Position Script - Quick-Take Mini-Tutorial

答案 1 :(得分:0)

  

试试这个...希望它有所帮助。

    $("#divClick").click(function (e) {
            var posX = $(this).position().left;
            var posY = $(this).position().top;
            var cursorX = (e.pageX - posX);
            var cursorY = (e.pageY - posY);
            //cursorX, cursorY is the absolute position of the mouse pointer
});