如何在角度2的视口中检查元素?

时间:2017-05-03 08:08:53

标签: angular angular2-routing

如何在角度2中检查元素是否在视口中?我试过很多npm包。但不行。如何检查元素是否在视口中?如果元素在视口中,我想在页面滚动上调用API吗?

我有三个标签。我必须检查选项卡是否处于活动状态且元素是否在视口中。怎么检查?

3 个答案:

答案 0 :(得分:1)

如果元素在视口上,我使用' jQuery-viewport-checker '来执行各种任务。它对我有用。这可能会对您有所帮助:

如果您没有在角度2项目中使用“jQuery”,请执行以下操作: https://stackoverflow.com/a/42295505/7532440

您必须使用'Bower'安装'jQuery-viewport-checker'并将其添加到'angular-cli.json'文件中的'Scripts',就像您在链接中安装'jQuery'一样我提供了。

CMD:

bower install jQuery-viewport-checker
'angular-cli.json'中的

"scripts": [
      "../bower_components/jquery/dist/jquery.min.js",
      "../bower_components/jQuery-viewport-checker/dist/jquery.viewportchecker.min.js"
  ]

现在你可以使用'jQuery-viewport-checker'

更多信息: https://github.com/dirkgroenen/jQuery-viewport-checker

您的app.component.ts将如下所示:

import { Component, OnInit } from '@angular/core';
declare var $:any;

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'app works!';

 ngOnInit(){

        $(document).ready(function(){
        $("p").click(function(){
        $(this).hide();
    });
    });


        $('.dummy').viewportChecker({
            classToAdd: 'visible', // Class to add to the elements when they are visible,
            classToAddForFullView: 'full-visible', // Class to add when an item is completely visible in the viewport
            classToRemove: 'invisible', // Class to remove before adding 'classToAdd' to the elements
            removeClassAfterAnimation: false, // Remove added classes after animation has finished
            offset: [100], // The offset of the elements (let them appear earlier or later). This can also be percentage based by adding a '%' at the end
            invertBottomOffset: true, // Add the offset as a negative number to the element's bottom
            repeat: false, // Add the possibility to remove the class if the elements are not visible
            callbackFunction: function(elem, action){}, // Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
            scrollHorizontal: false // Set to true if your website scrolls horizontal instead of vertical.
    });
 }

}

此类“可见”将在ViewPort中的元素“.dummy”类中添加。您应该根据需要更多地探索它(其他参数) 因此,您可以编写HTML代码。 我希望它有所帮助。

<强>更新

如果出错,请尝试以下方法(因为这些对问题的作者有效):

1):尝试更改端口ng serve --port 4200到4208(或任何其他端口)

2):将视口检查器代码放在文档中,就像这样:

jQuery(document).ready(function(){ 
      $('.dummy').viewportChecker({
            classToAdd: 'visible', // Class to add to the elements when they are visible,
            classToAddForFullView: 'full-visible', // Class to add when an item is completely visible in the viewport
            classToRemove: 'invisible', // Class to remove before adding 'classToAdd' to the elements
            removeClassAfterAnimation: false, // Remove added classes after animation has finished
            //offset: [100], // The offset of the elements (let them appear earlier or later). This can also be percentage based by adding a '%' at the end
            invertBottomOffset: true, // Add the offset as a negative number to the element's bottom
            repeat: false, // Add the possibility to remove the class if the elements are not visible
            callbackFunction: function(elem, action){}, // Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
            scrollHorizontal: false // Set to true if your website scrolls horizontal instead of vertical.
    });
 });

并删除偏移量:[100]

答案 1 :(得分:0)

我暂时没有使用它,但可能是您正在寻找的东西(根据您的需要进行重构):

export function getY(element: HTMLElement) {
  let y = element.offsetTop;

  while (element.offsetParent && element.offsetParent != document.body) {
    element = <HTMLElement>element.offsetParent;
    y += element.offsetTop;
  }
  return y;
}

export function getElementOnScreen(selector: string, delta: number = 0.3): any {
  let windowH = self.innerHeight;
  let windowY = self.pageYOffset;
  let margin = windowH * delta;

  return Array
    .from(document.querySelectorAll(selector))
    .find(el => {
      let elementY = getY(el as HTMLElement);
      let elementH = el.clientHeight;

      let topOnScreen = (elementY - windowY) <= margin;
      let bottomOnScreen = (windowY + margin) <= (elementY + elementH);

      return topOnScreen && bottomOnScreen;
    });
}

export function onScreen$(selector: string): Observable<boolean> {
  return Observable
    .fromEvent(window, 'scroll')
    .throttleTime(100)
    .map(event => getElementOnScreen(selector))

    .do(element => call.api(element))

    .map(Boolean)
    .distinctUntilChanged()
}

使用示例:

<div id="test" [class.i-am-in-viewport]="onScreen$('div#test') |async" />

答案 2 :(得分:0)

在angular中使用jQuery并不是一个好方法。

您可以使用交叉观察器API来实现此目的。

我已经使用Youtube Iframe API创建了一个演示应用程序,该应用程序在视频位于视口中时播放,在视频不在视口中时暂停。

工作演示

实时演示:-https://angular-viewport-intersection-observer-youtube.stackblitz.io

实时编辑:-https://stackblitz.com/edit/angular-viewport-intersection-observer-youtube

使用的包裹

https://github.com/thisissoon/angular-inviewport