繁体   English   中英

Angular 4 | window.scrollTo();工作不正常

[英]Angular 4 | window.scrollTo(); is not working properly

目前,我正在尝试自动滚动到我在我的Typescript中使用的HTML页面的顶部。

 window.scrollTo(0 , 0);

并尝试自动向下滚动到HTML页面的底部

 window.scrollTo( 0 , document.body.scrollHeight);
  • 我试图在HTTP响应后滚动顶部。

 openPDFVievwer(data) {
  this.obj= JSON.parse(data._body);
  document.getElementById('spinner').style.display = 'none';
  window.scrollTo( 0 , 0);
}
  • 当我在渲染另一个组件后尝试滚动底部时。

searchData(data) {
    this.document = data;
    this.searchResultDiv = true; // where component will be rendered
    window.scrollTo( 0 , document.body.scrollHeight);
  }

但是,两者似乎都没有用。

有什么我做错了吗?

试试html

<div #list [scrollTop]="list.scrollHeight"></div>

解决方案2

在Component id="scrollId"定义为html id="scrollId"

const element = document.querySelector('#scrollId');
element.scrollIntoView();

以上解决方案对我不起作用,请尝试以下代码:

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();
});
   }

回答角2+

这很简单,只需创建一个任何元素

例如<span id="moveTop"></span>仅将id添加到元素中或使用已存在的Id, 您必须在其中移动top,down,mid等。

并在特定事件上添加此方法,就像我想在编辑时移动顶部作为我的列表列表太多。

 gotoTop() {

   var scrollElem= document.querySelector('#moveTop');
   scrollElem.scrollIntoView();  
  }

或者如果要将Id作为参数发送,只需创建可选参数即可

gotoTop(elementId?: string) {

    if (elementId != null) {
        var element = document.querySelector(elementId);
        element.scrollIntoView();
    } 
    else {
        var element = document.querySelector('#moveTop');
        element.scrollIntoView();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM