0

I want my code to detect and trigger a custom function when user click within the coordinates of a rectangular.

IF the coordinates of Rectangle are already know.

I tried this code

W = $(el).width();
   H = $(el).height();
   X = $(el).position().left;
   Y = $(el).position().top;

But not able to detect it.

Example

Consider this. I want to detect and trigger function within these coordinates.

http://www.mathopenref.com/coordrectangle.html

Getting mouse coordinates is easy:-

$('canvas').mousemove(function(e){
    drawPaddle(e.pageX, e.pageY);
});


function drawPaddle(paddleX, paddleY) {
    c.beginPath();
    c.rect(paddleX, paddleY, 150, 10);
    c.closePath();
    c.fill();
}

How do I detect if user click within coordinates of my rectangle?

4

2 に答える 2

0

クリックイベントで直接マウスの位置を確認できます。それを長方形の座標と比較してください。

$(document).mousedown(function(e) {
   var x = e.pageX;
   var y = e.pageY; 

    if((x >= X && x <= X+W) &&
       (y >= Y && y <= Y+H))
        alert("in");
});

var el = "#div1";
var W = $(el).width();
var H = $(el).height();
var X = $(el).position().left;
var Y = $(el).position().top; 

私のjsfiddleをチェックしてください。

于 2012-04-19T13:22:14.957 に答える
0

このようなもの

var mouseX;
var mouseY;


$(el).mousemove(function(e){
    mouseX = e.pageX;
    mouseY = e.pageY;
});

$(el).click(function(e)
{
    W = $(el).width();
    H = $(el).height();
    X = $(el).position().left;
    Y = $(el).position().top;

    if (mouseX>X   && 
        mouseY>Y   && 
        mouseX<X+W && 
        mouseY<Y+H)
    {
        //do something
    }
});

多少の調整は必要かもしれませんが…

于 2012-04-19T13:17:23.227 に答える