Frage

I wanna make the ball bounce when it hit the board. So I have to get the board pixels to make it bounce when the ball hit the board. I tried this way but it didn't works. Here is my code Javascript code

var xboard = document.getElementById(board)
var movx = parseInt(xboard.style.left)

Image code

<img id="board" style="z-index: 0; left: 300;position: absolute; top: 600px" align=baseline border=0 hspace=0 src="design/board.gif">

When I tried to get the pixels by

alert(movx)

It said "Undefined" at the alert box. Could anyone help me?

War es hilfreich?

Lösung

This method gives you the coordinates of control passed

<img id="board" style="z-index: 0; left: 300;position: absolute; top: 600px" align=baseline border=0 hspace=0 src="design/board.gif">

function findPos(obj){
var curleft = 0;
var curtop = 0;

if (obj.offsetParent) {
    do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
       } while (obj = obj.offsetParent);

    return {X:curleft,Y:curtop};
}
}

findPos(document.getElementById('board'));
alert(curleft);
alert(curtop);

For more details here

Andere Tipps

I think you need to declare the position with px:

left: 300px

Seems to work: http://jsfiddle.net/p2gRq/

You are trying to use an actual element instead of it's id.

Change this:

var xboard = document.getElementById(board);

to:

var xboard = document.getElementById('board');

And make sure you're not trying to access board before it exists.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top