[英]I am trying to make typewriter effect in angular
我正在嘗試用 js 制作打字機
private i: number = 0;
private text: string = "hello stack";
private timer: number = 50;
typeWriter() {
console.log(this.text.length);
console.log(this.i);
if (this.i < this.text.length) {
document.querySelector(".quotes").innerHTML += this.text[0];
this.i++;
setTimeout(this.typeWriter, this.timer);
}
}
像這樣的東西,但在打印 h 或第一次調用之后它給了我錯誤無法讀取未定義的屬性“長度”。 並且 i 的值也沒有更新。
您需要使用bind
或箭頭 function 表示法在回調中使用this
關鍵字來引用 class 成員變量。 如果不是, this
關鍵字指的是function的scope。
嘗試以下
typeWriter() {
console.log(this.text.length);
console.log(this.i);
if (this.i < this.text.length) {
document.querySelector(".quotes").innerHTML += this.text[0];
this.i++;
setTimeout(this.typeWriter.bind(this), this.timer);
}
}
或者
typeWriter() {
console.log(this.text.length);
console.log(this.i);
if (this.i < this.text.length) {
document.querySelector(".quotes").innerHTML += this.text[0];
this.i++;
setTimeout(() => this.typeWriter(), this.timer);
}
}
另外, this.text this.text[0]
不應該是this.text[this.i]
嗎? 此外,使用 Angular 時最好不要直接訪問 DOM。 您可以嘗試使用 Angular Renderer 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.