typescript 角 4 | window.scrollTo(); 工作不正常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47904434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 4 | window.scrollTo(); is not working properly
提问by Abhishek Ekaanth
Currently, I'm trying to automatically scroll to the top of the HTML page for which I'm using in my Typescript.
目前,我正在尝试自动滚动到我在 Typescript 中使用的 HTML 页面的顶部。
window.scrollTo(0 , 0);
and while trying to automatically scroll down to bottom of the HTML page
并尝试自动向下滚动到 HTML 页面的底部
window.scrollTo( 0 , document.body.scrollHeight);
- I'm trying to scroll top after an HTTP response.
- 我试图在 HTTP 响应后滚动顶部。
Code
代码
openPDFVievwer(data) {
this.obj= JSON.parse(data._body);
document.getElementById('spinner').style.display = 'none';
window.scrollTo( 0 , 0);
}
- when I'm trying to scroll bottom after rendering another component.
- 当我在渲染另一个组件后尝试滚动底部时。
Code
代码
searchData(data) {
this.document = data;
this.searchResultDiv = true; // where component will be rendered
window.scrollTo( 0 , document.body.scrollHeight);
}
but, both seem to be not working.
但是,两者似乎都不起作用。
Is there something that I'm doing wrong?
有什么我做错了吗?
回答by Shailesh Ladumor
try into html
尝试进入 html
<div #list [scrollTop]="list.scrollHeight"></div>
Solution 2
解决方案2
In Component
define id into html id="scrollId"
在组件中将 id 定义为 html id="scrollId"
const element = document.querySelector('#scrollId');
element.scrollIntoView();
回答by aravind balaji
Above solution wasn't working for me, Try this code:
以上解决方案对我不起作用,试试这个 代码:
import { Router, NavigationEnd } from '@angular/router';
constructor(private router: Router)
ngOnInit()
{
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
document.getElementsByTagName("app-website-nav")[0].scrollIntoView();
});
}
回答by Deva
Answer for angular 2+
角度 2+ 的答案
It's very simple, Just create an any element
很简单,只要创建一个any元素
e.g.
<span id="moveTop"></span>
or add just idinto the element or use already existed Id where you have to move top, down, midetc.
例如,
<span id="moveTop"></span>
或者只将 id 添加到元素中,或者使用已经存在的 Id,您必须在其中移动顶部、向下、中间等位置。
and add this method on specific event, like I want to move top when edit as my list list too much.
并在特定事件上添加此方法,就像我想在编辑列表列表太多时移到顶部一样。
gotoTop() {
var scrollElem= document.querySelector('#moveTop');
scrollElem.scrollIntoView();
}
or If you want to send Id as Parameter you simply just create Optional Parameter
或者,如果您想将 Id 作为参数发送,您只需创建可选参数
gotoTop(elementId?: string) {
if (elementId != null) {
var element = document.querySelector(elementId);
element.scrollIntoView();
}
else {
var element = document.querySelector('#moveTop');
element.scrollIntoView();
}
}