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
}
Run Code Online (Sandbox Code Playgroud)
css:
#a,#b,#c {
width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我试图查看event参数,但它是一个相当大的对象,我找不到不同元素之间的区别:
event.target对象应该包含区分这些块所需的所有内容,因为它是 对调度事件的对象的引用
console.log(event.target.id) // a, b or c
Run Code Online (Sandbox Code Playgroud)
为了确定当前显示的是哪个全高 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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要向块添加事件处理程序:
<div id="..." (scroll)="onScroll($event)">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
remove this
Run Code Online (Sandbox Code Playgroud)
如果部分的高度不固定,那么您可以使用 ViewChildren 获取对所有部分的引用:
html
<div #a
<div #b
<div #c
Run Code Online (Sandbox Code Playgroud)
ts
const areas = 'a,b,c';
class Component {
@ViewChildren(areas) sections: QueryList<ElementRef>;
Run Code Online (Sandbox Code Playgroud)
然后使用一些帮助程序检查特定部分是否在视口内:
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)
);
}
Run Code Online (Sandbox Code Playgroud)
用法:
@HostListener('window:scroll', ['$event'])
onScroll(event) {
const activeSection = this.sections.toArray()
.findIndex(section => isElementInViewport(section.nativeElement));
console.log(areas.split(',')[activeSection]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2171 次 |
| 最近记录: |