【问题标题】:window.scroll doesn't scroll accuratelywindow.scroll 不能准确滚动
【发布时间】:2019-11-13 17:34:23
【问题描述】:

滚动页面时我有粘性标题,它固定在页面顶部。当我单击标题页面中的菜单时,必须滚动到该特定 div。对于粘性标题,我使用 angular.for 滚动普通 java脚本 window.scroll()。但 window.scroll() 不能准确滚动。

//stickyheader.html

<div #stickyMenu [class.sticky]="sticky">
  <div class="header">

    <div class="navbar">
      <ul>
        <li><a>Home</a></li>

        <li><a (click)="scrollTo('candidate')">Candidate</a></li>
        <li><a (click)="scrollTo('client')">Client</a></li>
        <li><a (click)="scrollTo('user')">User</a></li>
      </ul>
    </div>


  </div>
</div>

//stickyhedaer.ts

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, HostListener } from '@angular/core';
import { TargetLocator } from 'selenium-webdriver';

@Component({
  selector: 'app-sticky-header',
  templateUrl: './sticky-header.component.html',
  styleUrls: ['./sticky-header.component.css']
})
export class StickyHeaderComponent implements OnInit, AfterViewInit                 {

  @ViewChild('stickyMenu') menuElement: ElementRef;

  sticky: boolean;
  elementPosition: any;
  myElement: ElementRef;
  constructor() {
    this.sticky = false;
  }

  ngAfterViewInit() {
   this.elementPosition = this.menuElement.nativeElement.offsetTop;
    console.log(this.menuElement);
  }

  @HostListener('window:scroll', ['$event'])
  handleScroll() {
    const windowScroll = window.pageYOffset;
   if (windowScroll >= this.elementPosition) {
      this.sticky = true;
      console.log(this.elementPosition + ' host listener scroll');
    } else {
      this.sticky = false;
    }
  }
  scrollTo(id: any) {
    console.log(id);
    id = document.getElementById(id);

    // id.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });

    const yCoordinate = id.getBoundingClientRect().top + window.pageYOffset;
    const yOffset = 70;
    window.scroll({
      top: yCoordinate - yOffset,
      behavior: 'smooth'
    });
}
}

//app.component.html

<div>

  <div class="content"></div>
  <app-sticky-header></app-sticky-header>
  <app-candidate></app-candidate>
  <app-client></app-client>     
  <app-user></app-user>
  <div class="content"></div>

</div>

【问题讨论】:

标签: javascript css angular


【解决方案1】:

我制作了一个与您的查询相关的 stackblitz 示例。在该标题中粘贴并滚动到该部分正常工作。我没有添加多个组件。而不是我在

中添加了文本

标记并为该部分提供相同的 id。

Working Stackblitz

【讨论】:

  • 用组件替换文本,它在那里工作正常,但在这里不起作用
  • 我通过用不同的组件替换文本来更新上面的 stackblitz。请检查并让我知道进一步的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多