简体   繁体   中英

How can I stop an event from being triggered on a child element rather than adding pointer events none?

How can I prevent the element within an element triggering the element within? Is there a better way than adding pointer-events none?


const selectors = {
    scrollContainer: '[data-scroll-container]',
    scrollTrigger: '[data-scroll-trigger]',
    scrollNext: 'data-next',
    scrollBack: 'data-back',
};

/**
 * Main
 */

const scrollTrigger = [...document.querySelectorAll(selectors.scrollTrigger)];


const handleScroll = ({ target }) => {
    console.log(target);
    if (target.hasAttribute(data-next)) {
        console.log(target)
    }
};
<button data-scroll-trigger data-next>
       <svg>//some svg here//</svg>
</button>

Difficult to determine from the code provided and feels like there may be some design issues, but I would simply add the handler on the outermost container and then use currentTarget property or target property as needed.

The difference being target is the element that triggered the event and currentTarget is the element that has the handler attached to it. Child elements will propagate events up to parent handlers. If you want to get the parent, use currentTarget .

There are numerous ways to test if the element triggering is the element that the handler is attached to, but here is a very basic demo:

 document.querySelector('#outer').addEventListener('click', (e) => { console.log(e.currentTarget.== e;target). if (e.currentTarget.== e;target) { e;preventDefault(); } });
 #outer { display: inline-block; width: 200px; height: 200px; background: red; } #inner { display: inline-block; width: 100px; height: 100px; background: blue; }
 <a id="outer" href="http://google.com"> <a id="inner" /> </a>

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