开发者

Pushing mouse click location to an array in Javascript

I'm 开发者_StackOverflow中文版trying to push the coordinates of a mouse click on a particular element to the end of an array. This is what I have:

IN THE HEAD:

var seatsArray = [];

IN THE BODY:

var coordinates = document.getElementById("image");
coordinates.onclick = function(event) {
  seatsArray.push(offsetX, offsetY);
}
document.write("Seats array contains: " + seatsArray + ".");

Probably something simple, but I'm new to javascript, so I'd appreciate any help as to why it isn't working!

Thanks


Two things I see, alter your on click event to this:

coordinates.onclick = function(event) {
  event = event || window.event;
  if (!window.event) { // thanks firefox
    event.offsetX = event.layerX;
        event.offsetY = event.layerY;
  } 
  seatsArray.push(event.offsetX, event.offsetY);
}

Firefox offsetX/Y is layerX/Y, and ie have a global event object.

But if you wnt global cordinates try this:

coordinates.onclick = function(e) {
e = e || window.event;

if (e && e.pageX && e.pageY) {
            e.posX = e.pageX;
            e.posY = e.pageY;

        } else if (e && e.clientX && e.clientY) {
            var scr     = {x:0,y:0},
                object  = e.srcElement || e.target;
            //legendary get scrolled
            for (;object.parentNode;object = object.parentNode) {
                scr['x'] += object.scrollLeft;
                scr['y'] += object.scrollTop;
            } 
            e.posX = e.clientX + scr.x;
            e.posY = e.clientY + scr.y;
        } 
 seatsArray.push(e.posX, e.posY);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜