angular - 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
参数,但它是一个相当大的对象,我找不到不同元素之间的区别:
解决方案
event.target对象应该包含区分这些块所需的所有内容,因为它是 对调度事件的对象的引用
console.log(event.target.id) // a, b or c
更新
为了确定当前显示的是哪个全高 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
更新 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]);
}
推荐阅读
- docker - 错误:在文件“./docker-compose.yml”中,服务“图像”必须是映射而不是字符串
- javascript - React-Bootstrap 表未显示使用 BootstrapTable 库
- spring-boot - rabbitmq 中给定队列中没有可用消息时的消费者线程状态
- debian - Debian Nagios NRPE 连接被拒绝
- python - 之字形四倍
- java - springfox swagger 生成不正确的基本 URL
- c++ - 设置项目根文件夹
- laravel - Laravel 删除关系并以一种方式创建新关系?
- azure-cloud-services - Microsoft Azure 云服务管理 API 失败并出现 401:未经授权的错误?
- c# - Xamarin.ios 不能在真正的 iOS 设备上运行,但它可以在模拟器上运行