Prevent firing the blur event if any one of its children receives focus

前端 未结 3 1350
猫巷女王i
猫巷女王i 2020-12-25 11:42

I have a div on a page that shows some info about a particular category (Image, Name etc).

When I click on the edit image it puts the category into edit mode which

3条回答
  •  不思量自难忘°
    2020-12-25 12:21

    I don't think there is any guarantee mousedown will happen before the focus events in all browsers, so a better way to handle this might be to use evt.relatedTarget. For the focusin event, the eventTarget property is a reference to the element that is currently losing focus. You can check if that element is a descendant of the parent, and if its not, you know focus is entering the parent from the outside. For the focusout event, relatedTarget is a reference to the element that is currently receiving focus. Use the same logic to determine if focus is fully leaving the parent:

    const parent = document.getElementById('parent');
    
    parent.addEventListener('focusin', e => {
        const enteringParent = !parent.contains(e.relatedTarget);
    
        if (enteringParent) {
            // do things in response to focus on any child of the parent or the parent itself
        }
    });
    
    parent.addEventListener('focusout', e => {
        const leavingParent = !parent.contains(e.relatedTarget);
    
        if (leavingParent) {
            // do things in response to fully leaving the parent element and all of its children
        }
    });
    

提交回复
热议问题