简体   繁体   English

如何在多个 div 上捕获鼠标事件

[英]How to catch mouse event over multiple divs

I have many components that are on top of each other, and I need to add a listener so when a mouse pointer is in bounds of these components every component will do something.我有许多相互重叠的组件,我需要添加一个侦听器,因此当鼠标指针位于这些组件的范围内时,每个组件都会做一些事情。

I tried with mouseover, mouseenter, mousemove, etc. but these events works only on the component that is on top, not on all of them.我尝试使用 mouseover、mouseenter、mousemove 等,但这些事件仅适用于顶部的组件,而不适用于所有组件。 ex html:前 html:

<div class="container">
    <app-child></app-child>
    <app-child></app-child>
    <app-child></app-child>
    <app-child></app-child>
</div>

ex css:前 css:

.container > * {
    position: absolute;
    left: 0;
    top: 0;
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

ex app-child.component.ts ex app-child.component.ts

@Component({
    selector: 'app-child',
    template: '<div></div>'
})
ChildComponent {
    
    // Here some function that needs to run if mouse pointer is in bound of this element

}

if you want the children to do something如果你想让孩子们做点什么

parent.component.html父组件.html

<div class="container" (mouseenter)="doSomethingFunction()" (mouseleave)="stopDoSomething()>
    <app-child [doSomething]="doSomething"></app-child>
    <app-child [doSomething]="doSomething"></app-child>
    <app-child [doSomething]="doSomething"></app-child>
    <app-child [doSomething]="doSomething"></app-child>
</div>

parent.component.ts父组件.ts

@Component({
    selector: 'app-child',
    template: '<div></div>'
})
ParentComponent {

   
    doSomething = false;
    doSomethingFunction(e) {
        doSomething = true;
    }

    stopDoSomething(e) {
        doSomething = false;      
    }

}

child.component.ts child.component.ts

@Component({
    selector: 'app-child',
    template: '<div></div>'
})
ChildComponent {
    @Input() doSomething: boolean

    
    ngOnInit() {
         if(doSomething) {
             doSomethingElse();
         } else {
             stopDoingThings();
         }
    }

}

if you have to do something to the children如果你必须对孩子们做点什么

parent.component.html父组件.html

<div class="container" (mouseenter)="doSomething($event)">
    <app-child></app-child>
    <app-child></app-child>
    <app-child></app-child>
    <app-child></app-child>
</div>

parent.component.ts父组件.ts

@Component({
    selector: 'app-child',
    template: '<div></div>'
})
ParentComponent {

    
    doSomething(e) {
        for(const child in Array.from(e.target.children) {
            doSomethingElse(child);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM