html - 打字稿文件中的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 文件中输入此代码,一切正常。
欢迎任何想法或建议。
解决方案
推荐阅读
- python - 为什么我的代码将相同的字典对输出到文本文件中?
- python - yFinance - 获取所有符号
- mysql - 如何将几个单词放入mysql列
- javascript - Javascript开关未触发
- python - 一列python pandas的条件总和
- javascript - 我在 React/Java 中有一个字符编码程序。一切都设置为 UTF-8,但我的一个字符显示不正确
- python - 如何更改我的代码,以使输出中的值仅显示一次,而不是使用随机数多次显示?
- javascript - Node.JS 处理全局事件监听器
- excel - Excel JavaScript自定义函数在加载电子表格后启动两次?
- javascript - 我在 HTMLLIElement 处收到未定义的“无法读取属性“切换”。
`