Angular 6:如何根据滚动突出显示导航栏上的元素?

Posted

技术标签:

【中文标题】Angular 6:如何根据滚动突出显示导航栏上的元素?【英文标题】:Angular 6: How to highlight element on navbar depending on scroll? 【发布时间】:2019-06-24 01:31:20 【问题描述】:

我正在 Angular 6 中制作一个页面。这是一个简单的页面,我想根据滚动情况突出显示 navbar

这是我的代码:

.sticky 
  position: sticky;
  top: 0;

#i ul 
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: blue;


#i li 
  float: left;


#i li a 
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;


#i li a:hover 
  border-radius: 0px 0px 10px 10px;
  background-color: rgb(43, 137, 226);


/* #i 
  margin: 0px 0px 40px 0px;
 */

#footer-id 
  background-color:blue;
<span id="i">
  <ul class="sticky">
    <li id="i"><a class="active" href="#">Home</a></li>
    <li><a href="#news" (click)="scrollToElement(new)">News</a></li>
    <li><a href="#contact" (click)="scrollToElement(con)">Contact</a></li>
    <li><a href="#about" (click)="scrollToElement(about)">About</a></li>

    <ul class="nav navbar-nav pull-right">
      <li class="nav"><a href="#">Contact</a></li>
    </ul>
    <ul class="nav navbar-nav pull-right">
      <li class="nav">
        <a href="#ta" (click)="scrollToElement(con)">Target</a>
      </li>
    </ul>
  </ul>
</span>

<div class="container" style="margin-bottom: 20px;">
  <div #home>
    <br />
    <br />
    <h1>Home</h1>
    <p>You contact us here. Thank for your greatness</p>
    <p>
      Welcome to the Random Phrase and Idiom Generator. There will be times when
      you may need more than a random word for what you want to accomplish, and
      this free online tool can help. The use of this tool is quite simple. All
      you need to do is indicate the number of random phrases you'd like to be
      displayed, and then hit the "Generate Random Phrases" button. Once done,
      your chosen number of idioms will be displayed along with the meaning of
      the idiom.
    </p>
    <p>
      Welcome to the Random Phrase and Idiom Generator. There will be times when
      you may need more than a random word for what you want to accomplish, and
      this free online tool can help. The use of this tool is quite simple. All
      you need to do is indicate the number of random phrases you'd like to be
      displayed, and then hit the "Generate Random Phrases" button. Once done,
      your chosen number of idioms will be displayed along with the meaning of
      the idiom.
    </p>
  </div>
  <div #con>
    <br />
    <br />
    <h1>Contact</h1>
    <p>You contact us here. Thank for your greatness</p>
    <p>
      Idioms are a wonderful part of the English language that give it a lot of
      flavor. They force people to know more than the literal meaning of words.
      Idioms are commonly used phrases which have a meaning completely different
      than their literal meaning. This can be quite confusing to those who
      aren't familiar with the idiom and those who are studying English.
    </p>
    <p>
      Idioms are a wonderful part of the English language that give it a lot of
      flavor. They force people to know more than the literal meaning of words.
      Idioms are commonly used phrases which have a meaning completely different
      than their literal meaning. This can be quite confusing to those who
      aren't familiar with the idiom and those who are studying English.
    </p>
  </div>

  <div #new>
    <br />
    <br />
    <h1>News</h1>
    <p>This are new from us</p>
    <p>
      Using this tool can be excellent practice for students studying English as
      a second language because it gives the literal meaning of each phrase.
      This allows them to see the phrase and its meaning at the same time. While
      there are long idiom lists available online, trying to navigate through
      them all on a single page can be daunting. Being able to create the exact
      number of random idioms which best suits your learning needs is a
      advantage this tool has over standard phrase list. In this way, this tool
      provides an excellent way for those learning English to practice their
      knowledge of English idioms and to learn new ones in the process.
    </p>
    <p>
      Using this tool can be excellent practice for students studying English as
      a second language because it gives the literal meaning of each phrase.
      This allows them to see the phrase and its meaning at the same time. While
      there are long idiom lists available online, trying to navigate through
      them all on a single page can be daunting. Being able to create the exact
      number of random idioms which best suits your learning needs is a
      advantage this tool has over standard phrase list. In this way, this tool
      provides an excellent way for those learning English to practice their
      knowledge of English idioms and to learn new ones in the process.
    </p>
  </div>

  <div #about>
    <br />
    <br />
    <h1>About</h1>
    <p>This are new from us</p>
    <p>
      It can also be a wonderful way for writers to brainstorm and spur more
      creativity in their writing. The tool can be used to get writing ideas
      flowing forcing the writer to use more creativity than they would with a
      single random word. For example, the writer can use the generated phrase
      to create a new paragraph or story. Since the writer has no idea what will
      appear, or even if they will be familiar with the idiom, it forces the
      writer to use creativity to incorporate it into what they're writing.
    </p>
    <p>
      It can also be a wonderful way for writers to brainstorm and spur more
      creativity in their writing. The tool can be used to get writing ideas
      flowing forcing the writer to use more creativity than they would with a
      single random word. For example, the writer can use the generated phrase
      to create a new paragraph or story. Since the writer has no idea what will
      appear, or even if they will be familiar with the idiom, it forces the
      writer to use creativity to incorporate it into what they're writing.
    </p>
  </div>
</div>

<!-- Footer -->
<footer class="page-footer font-small indigo" id="footer-id">
  <!-- Footer Links -->
  <div class="container text-center text-md-left">
    <!-- Grid row -->
    <div class="row">
      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Very long link 1</a></li>
          <li><a href="#!">Very long link 2</a></li>
          <li><a href="#!">Very long link 3</a></li>
          <li><a href="#!">Very long link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->

      <hr class="clearfix w-100 d-md-none" />

      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->

      <hr class="clearfix w-100 d-md-none" />

      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->

      <hr class="clearfix w-100 d-md-none" />

      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->
    </div>
    <!-- Grid row -->
  </div>
  <!-- Footer Links -->

  <!-- Copyright -->
  <div class="footer-copyright text-center py-3">
    © 2018 Copyright:
    <a href="https://mdbootstrap.com/education/bootstrap/"> MDBootstrap.com</a>
  </div>
  <!-- Copyright -->
</footer>

如何在滚动时突出显示导航栏元素?

我做了一些研究,看来我可以像这样使用 HostListener:

    @HostListener('window:scroll', ['$event'])
  scrollHandler(event) 
    console.log('Scroll Event');
    // console.log(event);
    const verticalOffset =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop ||
      0;

    console.log(verticalOffset);
  

但我仍然无法将滚动与 div 链接。有什么想法吗?

【问题讨论】:

你的意思是粘性导航? @Chellappan 我想在滚动时激活当前菜单导航栏。例如,当我滚动到联系人时,我希望导航栏激活联系人。 【参考方案1】:

这取决于您的项目有多复杂。以非常原始的方式,您可以执行以下操作:

使用 ngClass,您将“活动”类绑定到 currentActive 变量。

<li><a href="#" [ngClass]="'active': currentActive === 1">Home</a></li>
<li><a href="#news" [ngClass]="'active': currentActive === 2" (click)="scrollToElement(new)">News</a></li>
<li><a href="#contact" [ngClass]="'active': currentActive === 3" (click)="scrollToElement(con)">Contact</a></li>
<li><a href="#about" [ngClass]="'active': currentActive === 4" (click)="scrollToElement(about)">About</a></li>

现在,关于如何检查我们当前的滚动位置(当前 YOffset)。要获取我们当前的滚动位置,并将其绑定到滚动事件,我们可以简单地这样做:

@HostListener('window:scroll', ['$event'])
checkOffsetTop() 
  console.log(window.pageYOffset); // this will console log our scroll position

现在我们想要知道在什么 Y 位置是我们的锚点。为此,我们可以使用@ViewChild 装饰器。

@ViewChild('home') homeElement: ElementRef;
@ViewChild('con') conElement: ElementRef;
@ViewChild('new') newElement: ElementRef;
@ViewChild('about') aboutElement: ElementRef;

这只会将我们的引用绑定到我们的变量。为了检查它们的偏移量,我们想先渲染我们的视图,所以我们会收到正确的偏移量。因此,我们将使用 ngAfterViewInit

ngAfterViewInit() 
  this.homeOffset = this.homeElement.nativeElement.offsetTop;
  this.conOffset = this.conElement.nativeElement.offsetTop;
  this.newOffset = this.newElement.nativeElement.offsetTop;
  this.aboutOffset = this.aboutElement.nativeElement.offsetTop;

完整代码如下所示:

import  Component, AfterViewInit, ViewChild, ElementRef, HostListener  from '@angular/core';

@Component(
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
)
export class AppComponent implements AfterViewInit 
  @ViewChild('home') homeElement: ElementRef;
  @ViewChild('con') conElement: ElementRef;
  @ViewChild('new') newElement: ElementRef;
  @ViewChild('about') aboutElement: ElementRef;

  public currentActive = 0;
  public homeOffset: Number = null;
  public conOffset: Number = null;
  public newOffset: Number = null;
  public aboutOffset: Number = null;

  ngAfterViewInit() 
    this.homeOffset = this.homeElement.nativeElement.offsetTop;
    this.conOffset = this.conElement.nativeElement.offsetTop;
    this.newOffset = this.newElement.nativeElement.offsetTop;
    this.aboutOffset = this.aboutElement.nativeElement.offsetTop;
  

  scrollToElement() 
    // scrollToElement Code :)
  

  @HostListener('window:scroll', ['$event'])
  checkOffsetTop() 
    if (window.pageYOffset >= this.homeOffset && window.pageYOffset < this.conOffset) 
      this.currentActive = 1;
     else if (window.pageYOffset >= this.conOffset && window.pageYOffset < this.newOffset) 
      this.currentActive = 2;
     else if (window.pageYOffset >= this.newOffset && window.pageYOffset < this.aboutOffset) 
      this.currentActive = 3;
     else if (window.pageYOffset >= this.aboutOffset) 
      this.currentActive = 4;
     else 
      this.currentActive = 0;
    
  
.sticky 
    position: sticky;
    top: 0;
  

  .active 
      font-weight: bold !important;
      color: red !important;
      font-size: 1.2rem !important;
  

  #i ul 
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: blue;
  
  
  #i li 
    float: left;
  
  
  #i li a 
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
  
  
  #i li a:hover 
    border-radius: 0px 0px 10px 10px;
    background-color: rgb(43, 137, 226);
  
  
  /* #i 
    margin: 0px 0px 40px 0px;
   */
  
  #footer-id 
    background-color:blue;
  
<span id="i">
  <ul class="sticky">
    <li><a href="#" [ngClass]="'active': currentActive === 1">Home</a></li>
    <li><a href="#news" [ngClass]="'active': currentActive === 2" (click)="scrollToElement(new)">News</a></li>
    <li><a href="#contact" [ngClass]="'active': currentActive === 3" (click)="scrollToElement(con)">Contact</a></li>
    <li><a href="#about" [ngClass]="'active': currentActive === 4" (click)="scrollToElement(about)">About</a></li>

    <ul class="nav navbar-nav pull-right">
      <li class="nav"><a href="#">Contact</a></li>
    </ul>
    <ul class="nav navbar-nav pull-right">
      <li class="nav">
        <a href="#ta" (click)="scrollToElement(con)">Target:  currentActive </a>
      </li>
    </ul>
  </ul>
</span>

<div class="container" style="margin-bottom: 20px;">
  <div #home>
    <br />
    <br />
    <h1>Home | offset:  homeOffset </h1>
    <p>You contact us here. Thank for your greatness</p>
    <p>
      Welcome to the Random Phrase and Idiom Generator. There will be times when
      you may need more than a random word for what you want to accomplish, and
      this free online tool can help. The use of this tool is quite simple. All
      you need to do is indicate the number of random phrases you'd like to be
      displayed, and then hit the "Generate Random Phrases" button. Once done,
      your chosen number of idioms will be displayed along with the meaning of
      the idiom.
    </p>
    <p>
      Welcome to the Random Phrase and Idiom Generator. There will be times when
      you may need more than a random word for what you want to accomplish, and
      this free online tool can help. The use of this tool is quite simple. All
      you need to do is indicate the number of random phrases you'd like to be
      displayed, and then hit the "Generate Random Phrases" button. Once done,
      your chosen number of idioms will be displayed along with the meaning of
      the idiom.
    </p>
  </div>
  <div #con>
    <br />
    <br />
    <h1>Contact</h1>
    <p>You contact us here. Thank for your greatness</p>
    <p>
      Idioms are a wonderful part of the English language that give it a lot of
      flavor. They force people to know more than the literal meaning of words.
      Idioms are commonly used phrases which have a meaning completely different
      than their literal meaning. This can be quite confusing to those who
      aren't familiar with the idiom and those who are studying English.
    </p>
    <p>
      Idioms are a wonderful part of the English language that give it a lot of
      flavor. They force people to know more than the literal meaning of words.
      Idioms are commonly used phrases which have a meaning completely different
      than their literal meaning. This can be quite confusing to those who
      aren't familiar with the idiom and those who are studying English.
    </p>
  </div>

  <div #new>
    <br />
    <br />
    <h1>News</h1>
    <p>This are new from us</p>
    <p>
      Using this tool can be excellent practice for students studying English as
      a second language because it gives the literal meaning of each phrase.
      This allows them to see the phrase and its meaning at the same time. While
      there are long idiom lists available online, trying to navigate through
      them all on a single page can be daunting. Being able to create the exact
      number of random idioms which best suits your learning needs is a
      advantage this tool has over standard phrase list. In this way, this tool
      provides an excellent way for those learning English to practice their
      knowledge of English idioms and to learn new ones in the process.
    </p>
    <p>
      Using this tool can be excellent practice for students studying English as
      a second language because it gives the literal meaning of each phrase.
      This allows them to see the phrase and its meaning at the same time. While
      there are long idiom lists available online, trying to navigate through
      them all on a single page can be daunting. Being able to create the exact
      number of random idioms which best suits your learning needs is a
      advantage this tool has over standard phrase list. In this way, this tool
      provides an excellent way for those learning English to practice their
      knowledge of English idioms and to learn new ones in the process.
    </p>
  </div>

  <div #about>
    <br />
    <br />
    <h1>About</h1>
    <p>This are new from us</p>
    <p>
      It can also be a wonderful way for writers to brainstorm and spur more
      creativity in their writing. The tool can be used to get writing ideas
      flowing forcing the writer to use more creativity than they would with a
      single random word. For example, the writer can use the generated phrase
      to create a new paragraph or story. Since the writer has no idea what will
      appear, or even if they will be familiar with the idiom, it forces the
      writer to use creativity to incorporate it into what they're writing.
    </p>
    <p>
      It can also be a wonderful way for writers to brainstorm and spur more
      creativity in their writing. The tool can be used to get writing ideas
      flowing forcing the writer to use more creativity than they would with a
      single random word. For example, the writer can use the generated phrase
      to create a new paragraph or story. Since the writer has no idea what will
      appear, or even if they will be familiar with the idiom, it forces the
      writer to use creativity to incorporate it into what they're writing.
    </p>
  </div>
</div>

<!-- Footer -->
<footer class="page-footer font-small indigo" id="footer-id">
  <!-- Footer Links -->
  <div class="container text-center text-md-left">
    <!-- Grid row -->
    <div class="row">
      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Very long link 1</a></li>
          <li><a href="#!">Very long link 2</a></li>
          <li><a href="#!">Very long link 3</a></li>
          <li><a href="#!">Very long link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->

      <hr class="clearfix w-100 d-md-none" />

      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->

      <hr class="clearfix w-100 d-md-none" />

      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->

      <hr class="clearfix w-100 d-md-none" />

      <!-- Grid column -->
      <div class="col-md-3 mx-auto">
        <!-- Links -->
        <h5 class="font-weight-bold text-uppercase mt-3 mb-4">Links</h5>

        <ul class="list-unstyled">
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!-- Grid column -->
    </div>
    <!-- Grid row -->
  </div>
  <!-- Footer Links -->

  <!-- Copyright -->
  <div class="footer-copyright text-center py-3">
    © 2018 Copyright:
    <a href="https://mdbootstrap.com/education/bootstrap/"> MDBootstrap.com</a>
  </div>
  <!-- Copyright -->
</footer>

记住。这是您问题的非常原始的解决方案。这完全取决于您的应用程序/组件的复杂程度。无论如何,我希望这能解决一些问题。

【讨论】:

你也可以试试 scrolledIndexChange from CdkVirtualScrollViewport 获取列表索引的偏移量(而不是上面的 checkOffsetTop 函数) 如果您的导航栏组件与页面内容组件分开怎么办?

以上是关于Angular 6:如何根据滚动突出显示导航栏上的元素?的主要内容,如果未能解决你的问题,请参考以下文章

如何在导航栏上突出显示活动路线?

如何在导航栏上添加徽标?

如何在导航栏上为单个视图上的不同按钮设置标题?

如何根据活动页面突出显示导航菜单项(具有:: after伪元素)。

如何强制 ag-grid 滚动到选定/突出显示的行位置

更改导航 ID 以突出显示当前页面 ASP.NET 的编程解决方案