簡體   English   中英

使用JavaScript將定時事件綁定到DOM對象

[英]Binding timed events to DOM object with JavaScript

我正在嘗試將setInterval事件綁定到DOM對象。 在此示例中,HTML和CSS已過時。 嘗試了不同的方法,但似乎沒有一個起作用。 我在這里想念什么?

 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); } } 

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