angular - Angular 2 scrollIntoView 不滚动
问题描述
footerWrapperTop
我的HTML 中有一个 id 的 DIV 。
我的组件中有以下 TypeScript:
ngAfterViewInit(): void {
try {
this.sFragment = 'footerWrapperTop';
const nativeElement = document.querySelector('#' + this.sFragment);
nativeElement.scrollIntoView();
} catch (e) { } }
但是,页面在运行时不会向下滚动到页脚。我究竟做错了什么?
如果我console.dir(nativeElement);
在控制台中显示 DIV。
解决方案
您可以使用Angular 的渲染器
根据Angular 的官方文档为 selectRootElement提供第二个参数,因为它用于保存您的内容
句法:
selectRootElement(selectorOrNode: any, preserveContent?: boolean): any
已创建Stackblitz Demo供您参考
import { Component, AfterViewInit, Renderer2 } from '@angular/core';
@Component({...})
export class ChildComponent implements AfterViewInit {
sFragment: string;
constructor(private renderer: Renderer2) {}
ngAfterViewInit(): void {
this.sFragment = 'footerWrapperTop';
const element = this.renderer.selectRootElement(`#${this.sFragment}`, true); // true to indicate that you will preserve the content
element.scrollIntoView({ behavior: 'smooth' }); // for smooth scrolling
}
}
推荐阅读
- python - 下标 sqlalchemy 表列
- node.js - 将 gridfs 与 node rest API 一起使用
- python - 如何将参数从 Twisted 中的 deferred 添加到 addTimeout 函数
- websphere - 用于访问安装在 websphere 应用程序服务器 9 中的应用程序的 URL
- mobile - 使用 Flutter 进行 Salesforce 开发
- google-chrome-extension - chrome 扩展是否可以通过 Windows 集成凭据?
- javascript - 从 DOM 中删除 $obj 而不从该对象中删除绑定事件侦听器
- java - 我的 Java 代码有什么问题??(初学者)
- ffmpeg - 如何将 ffmpeg 与 mjpeg_vaapi 编码器一起使用(带硬件加速)?
- html - :hover 在 html 和 css 中的用法