首页 > 解决方案 > Angular,检测当前屏幕在哪个元素上滑动

问题描述

Angular@HostListener可以检测鼠标移动。但我希望能够识别我正在滑动的元素的间隔。

例如:

零件:

 @HostListener('window:scroll', ['$event']) 
      onScroll(event) {
      console.log(event);
      //When the mouse is scrolled, identify which element is currently displayed on the browser window, A or B or C
      //element A,B,C height is not fixed
      }

CSS:

#a,#b,#c {
 width: 100%;
}

html:

<body>
    <div id="a" (scroll)="onScroll($event)">
    Block A
      .
      .
      (more element)
    </div>
    <div id="b" (scroll)="onScroll($event)">
    Block B
      .
      .
      (more element)
    </div>
    <div id="c" (scroll)="onScroll($event)">
    Block C
      .
      .
      (more element)
    </div>
</body>

我试图查看event参数,但它是一个相当大的对象,我找不到不同元素之间的区别:

在此处输入图像描述

标签: angular

解决方案


event.target对象应该包含区分这些块所需的所有内容,因为它是 对调度事件的对象的引用

console.log(event.target.id) // a, b or c

Ng 运行示例

更新

为了确定当前显示的是哪个全高 div 块,您可以进行一些数学运算,例如:

areas = ['a', 'b', 'c']

@HostListener('window:scroll', ['$event'])
onScroll(event) {
  const activeElem = this.areas[
      Math.floor(window.pageYOffset/ document.documentElement.clientHeight)
  ];
  console.log(activeElem);
}

请注意,您不需要将事件处理程序添加到您的块:

<div id="..." (scroll)="onScroll($event)">
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
              remove this

Ng 运行示例

更新 2

如果部分的高度不固定,那么您可以使用 ViewChildren 获取对所有部分的引用:

html

<div #a

<div #b

<div #c

ts

const areas = 'a,b,c';

class Component {
    @ViewChildren(areas) sections: QueryList<ElementRef>; 

然后使用一些帮助器检查特定部分是否在视口内:

function isElementInViewport(el) {
  var rect = el.getBoundingClientRect();

  return (
    rect.bottom >= 0 &&
    rect.right >= 0 &&
    rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.left <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

用法:

@HostListener('window:scroll', ['$event'])
onScroll(event) {
  const activeSection = this.sections.toArray()
     .findIndex(section => isElementInViewport(section.nativeElement));

  console.log(areas.split(',')[activeSection]);
}

Ng 运行示例


推荐阅读