如何复制函数以便我可以使用“this”在 onLoad 函数中。又名 this.onload?

发布于 2024-11-30 23:50:52 字数 1160 浏览 3 评论 0原文

当对象加载时,我希望它在页面上移动。动作并不是难点。我正在使用这段代码(或多或少)。

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()',100);
    }

问题是我不想通过 ID 获取元素,而是想使用“this”关键字。

我读了这篇相当有用的文章: http://www.quirksmode.org/js/this.html< /a> 并了解到我必须复制该函数,而不是引用它。

他们说执行此操作的语法是 element.onLoad="" 而不是 onload="" 但我仍然不明白为 element 编写什么。

任何建议都会有很大的帮助。 谢谢

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()',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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听,心雨的声音 2024-12-07 23:50:52

编写如下内容:

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

然后 moveImage() 中的 this 将是您加载的 img

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文