首页 > 解决方案 > 打字稿文件中的DOMDocument

问题描述

我有一个打字稿文件,我需要访问 DOM 文档,我的问题document.getElementByClassName('name')是未定义。如果我打印当然会显示在控制台上,但那是因为控制台正在读取实时文档。在我看来,打字稿文件不是或需要一些时间来完成。

我正在使用 vue3 与 vite 和 typescript,但我认为使用 vu3 或 vite 与这个问题无关。

文件结构为

在 vue 文件中,我调用const API = new ClassName(sections, option). 到目前为止,这里没有什么可报告的。但是在打字稿文件中,我有一个类可以处理来自 HTML 的窗口和文档,并且有时可以工作。

我的打字稿文件看起来像这样

export class ClassName {
    sections: number[]
    options: OptionsInterface
    current: number
    
    constructor(sections: number[], options: OptionsInterface){
      this.sections = sections
      this.options = options
      this.current = 0
      this.init()
    }

    init():void {
      this.setEvents()
    }

    setEvents(): void {
       document.addEventListener("wheel", (e) => this.handleWheel(e), false) // this works fine
    }

    handleWheel(e): void {
         //here find if is moving up or down nothing to report
     if (delta < 0) this.move('up')
     else this.move('down')
    }

    move(type: string): void {
      if (type === 'down') this.moveDown()
      else this.moveUp()
    }
    
    // the move up and move down do the same in different directions
    moveUp(): void {
      this.current ++;
      let next = this.current
      if (next > this.sections.length - 1) {
         next = this.sections.length - 1
         this.current = next;
      }
      if (next < this.sections.length) {
        this.moveTo(next, null, false)
      }
    }
 
    moveTo(element: number, callback, isMovementUp: boolean): void {
      if(element === null) return;
      if(element === 0) window.scrollTo({top: 0, behavior: 'smooth'})
      else document.getElementsByClassName('section')[element].scrollIntoView({behavior: 'smooth'}) // this one is not working
    }
   
}

up 代码是一个示例,因为我无法与您分享所有代码。如果我在浏览器中添加断点,这个不工作的步骤就会开始工作。如果我在 vue 文件中输入此代码,一切正常。

欢迎任何想法或建议。

标签: htmltypescript

解决方案


推荐阅读