【问题标题】:How to check the element is in viewport on angular 2?如何检查元素是否在角度 2 的视口中?
【发布时间】:2017-05-03 08:08:52
【问题描述】:

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

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

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

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

    如果您的 Angular 2 项目中没有“jQuery”,请按照此操作: https://stackoverflow.com/a/42295505/7532440

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

    命令:

    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]

    【讨论】:

    • 我同时使用 npm 和 bower,请查看此链接 stackoverflow.com/a/42295505/7532440
    • 您应该将 Bower 用于与 Web 相关的软件包。
    • 您是否按照安装 jQuery 的所有步骤进行操作? “脚本”中的路径(在 angular-cli.json 中)应该正确指向 jquery.min.js 文件。首先检查你的简单 jQuery 是否正在运行,然后尝试 viewPortChecker
    • 确保使用“declare var $:any;” (带声明)
    • bower install jquery --save bower jquery#* cached https://github.com/jquery/jquery-dist.git#3.2.1 bower jquery#* validate 3.2.1 against https://github.com/jquery/jquery-dist.git#* bower jquery#>=1.9.0 || >=2.0.0 cached https://github.com/jquery/jquery-dist.git#3.2.1 bower jquery#>=1.9.0 || >=2.0.0 validate 3.2.1 against https://github.com/jquery/jquery-dist.git#>=1.9.0 || >=2.0.0 bower no-json No bower.json file to save to, use bower init to create one
    【解决方案2】:

    我有一段时间没有使用它,但可能是您正在寻找的(重构它以满足您的需求):

    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" />
    

    【讨论】:

    • 我收到此错误[ts] Cannot find name 'getY'.
    • 这是对您的 api (; 只需将其删除,或用控制台日志替换
    • 例外:self.parentView.context.onScreen$ 不是函数
    • 您必须重构代码才能使用您的组件。这些只是独立的函数,但数学就在那里(;
    【解决方案3】:

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

    您可以使用intersection-observer 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 2015-09-05
      • 2018-07-10
      • 1970-01-01
      • 2022-01-13
      • 2019-04-16
      • 2019-02-12
      相关资源
      最近更新 更多