简体   繁体   English

使用JavaScript将定时事件绑定到DOM对象

[英]Binding timed events to DOM object with JavaScript

I'm trying to bind setInterval event to DOM objects. 我正在尝试将setInterval事件绑定到DOM对象。 HTML and CSS is obsolete in this example. 在此示例中,HTML和CSS已过时。 Tried different approaches but none seem to work. 尝试了不同的方法,但似乎没有一个起作用。 What am I missing here ? 我在这里想念什么?

 window.onload = function() { for (let index = 0; index < 20; index++) { let x = new Box(Math.floor((Math.random() * 100) + 1), index + (index * 10), Math.floor((Math.random() * 100) + 1), 5); } } var id = 0; class Box{ constructor(x, y, size, speed){ this.speed = speed; this.x = x; this.y = y; this.size = size; this.id = id; id++; this.spawn(); this.move(this.id); } spawn(){ let x = document.createElement("div"); x.setAttribute("id", this.id); x.setAttribute("class", "box"); x.style.top = this.y + 'px'; x.style.left = this.x + 'px'; x.style.width = this.size + 'px'; x.style.height = this.size + 'px'; document.body.appendChild(x); } move(id){ setInterval(function() { document.getElementById(id).style.left = this.speed + 'px'; this.speed += 5; }, 10); } } 

The this in setInterval doesnt refer to the object you want, you need to pass in this when calling move , also they dont have a position setInterval中的this不指向您想要的对象,您需要在调用move时传递此方法,它们也没有position

 window.onload = function() { for (let index = 0; index < 20; index++) { let x = new Box(Math.floor((Math.random() * 100) + 1), index + (index * 10), Math.floor((Math.random() * 100) + 1), 5); } } var id = 0; class Box{ constructor(x, y, size, speed){ this.speed = speed; this.x = x; this.y = y; this.size = size; this.id = id; id++; this.spawn(); this.move(this.id, this); } spawn(){ let x = document.createElement("div"); x.setAttribute("id", this.id); x.setAttribute("class", "box"); x.style.top = this.y + 'px'; x.style.left = this.x + 'px'; x.style.width = this.size + 'px'; x.style.height = this.size + 'px'; document.body.appendChild(x); } move(id, _this){ setInterval(function() { document.getElementById(id).style.left = _this.speed + 'px'; _this.speed += 5; }, 10); } } 
 div { position: relative; background-color: #f00; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM