gpt4 book ai didi

javascript - 如何解决 "Cannot read property ' scrollIntoView' of undefined"?

转载 作者:行者123 更新时间:2023-12-01 16:18:48 25 4
gpt4 key购买 nike

我想在单击 中的按钮时滚动到特定的 div Angular 7 ,下面是我正在使用的代码,但它在 stackblitz 中工作,但在我的项目中使用时显示错误。
“无法读取未定义的属性‘scrollIntoView’”。

https://stackblitz.com/edit/angular-scroll-local-variable?file=src%2Fapp%2Fscroll.component.ts

试试这个链接:https://stackblitz.com/edit/angular-scroll-local-variable-ja96uz?file=src%2Fapp%2Fapp.component.html

<button (click)="scroll(target)"></button>
<div #target>Your target</div>

在组件中:
scroll(el) {
el.scrollIntoView();
}

最佳答案

尝试提供scrollToAnchor方法的 Angular ViewportScroller服务

滚动.html

<button (click)="scroll('target')">Click to scroll</button>
<div id="target">Your target</div>

滚动.ts
import { Component, Input } from '@angular/core';
import { ViewportScroller } from '@angular/common';
@Component({
selector: 'scroll',
template: `
<button (click)="scroll('target')">Click to scroll</button>
<div id="target">Your target</div>
`,
styles: [`h1 { font-family: Lato; }`, `div { margin-top: 5000px; }`]
})
export class ScrollComponent {

constructor(private vps: ViewportScroller) {

}
scroll(id) {
this.vps.scrollToAnchor(id);
}
}

示例: https://stackblitz.com/edit/angular-scroll-local-variable-99hwvo

关于javascript - 如何解决 "Cannot read property ' scrollIntoView' of undefined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54340120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com