开发者

How to copy a function so that i can use "this" in an onLoad function. AKA this.onload?

When an object loads, I want it to move across the page. The movement is not the hard part. I am using this code (more or less) for that.

var x = 5; //Starting Location - left
var y = 5; //Starting Location - top
var dest_x = 300;  //Ending Location - left
var dest_y = 300;  //Ending Location - top
var interval = 10; //Move 10px every initialization

function moveImage() {
    //Keep on moving the image till the target is achieved
    if(x<dest_x) x = x + interval; 
    if(y<dest_y) y = y + interval;

    //Move the image to the new location
    document.getElementById("ufo").style.top  = y+'px';
    document.getElementById("ufo").style.left = x+'px';

    if ((x+interval < dest_x) && (y+interval < dest_y)) {
        //Keep on calling this function every 100 microsecond 
        //  till the target location is reached
        window.setTimeout('moveImage()开发者_StackOverflow',100);
    }

the thing is that I don't want to get my element by ID, instead, I want to use the "this" keyword.

I read this rather helpful article: http://www.quirksmode.org/js/this.html and learned that I have to copy the function, not reference it.

They said that the syntax to do this was element.onLoad="" instead of onload="" but I still don't understand what to write for element.

Any suggestions would be a big help. Thanks


Write something like this:

var image = document.createElement('img');
image.onload = moveImage;
image.src = 'test.jpg';

Then this in moveImage() will be your loaded img

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜