How are Shadow DOM events from under targeted?

后端 未结 1 1174
慢半拍i
慢半拍i 2020-12-16 22:46

I\'m trying to understand what events that originate in light DOM look like when received in shadow DOM via a element. I\'m reading the Shadow D

相关标签:
1条回答
  • 2020-12-16 23:23

    Events with shadow dom are tricky. I try to capture a braindump below.

    1. Is this the way it is supposed to work

    Yep. If you're testing in Chrome, you get native shadow dom.


    I wrote a section on event retargeting in the HTML5Rocks - Shadow DOM 301 article. Basically, retargeting means that events that originate in the shadow dom look like they come from the element itself.

    In your example, you're logging the event internal to the shadow dom, so it's still seen there. If you also add a 'click' listener outside of the element, the target will look as if it came from the element:

    <script>
      var el = document.querySelector('#custom-element');
      el.addEventListener('click', function(e) {
        console.log(e.target.tagName); // logs FOO-Bar
      });
    </script>
    

    http://jsbin.com/womususe/1/edit

    The 'click' event bubbles. This is why you see BUTTON in your top example. Why do you see it at all? You see it because the button is not part of your element's shadow dom. It's in the light dom and the target of the element. It's important to remember that light DOM nodes are still logically in the main document. They're not moved into the shadow dom, merely rendered at <content> insertion points.


    BTW, there are a couple of Polymerized fixes to your examples:

    1. this.shadowRoot.querySelector('#internalcontainer') -> this.$.internalcontainer. this.$.ID is Polymer's "automatic node finding" feature.
    2. You don't need to use addEventListener() at all. Instead , use <div id="internalcontainer" on-click="{{clickHandler}}">. This is a declarative event handler.
    0 讨论(0)
提交回复
热议问题