简体   繁体   中英

why dose events trigger for child element when chlid not defind with the events but parent has events defined

I have a image enclosed inside div. And i defined mouseover and mouseout events for parent.

<div id="leftnav" ng-mouseover="leftnavOver($event)" ng-mouseout="leftnavOut($event)" ng-mouseleave="leftnavOut($event)"><img width="20" src="images/left-arrow.png"></div>

angular code

$scope.leftnavOver = function ($event) {
    angular.element($event.target).css("background", "red")
}

$scope.leftnavOut = function ($event) {
    angular.element($event.target).css("background", "black")
}

why does events gets triggered for both div and img....

The mouseover/out event fires on the child and bubbles up. You can detect the source of the event by comparing $event.target with the source element. $event.target is the element that spawned the event (the img ).

You can also use mouseenter and mouseleave instead which does not bubble .

Because img is part of div . And event is bound on div .

To stop this, you can use stopPropagation as follow:

HTML

<div id="leftnav" ng-mouseover="leftnavOver($event)" ng-mouseout="leftnavOut($event)" ng-mouseleave="leftnavOut($event)">
    <img width="20" src="images/left-arrow.png" ng-mouseover="imgEvents()" ng-mouseout="imgEvents()" ng-mouseleave="imgEvents()" />
</div>

Javascript

$scope.imgEvents = function ($event) {
    angular.element($event.target).stopPropagation();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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