简体   繁体   中英

Why does clicking on the padding of an element's child makes the element the event.target?

I've thought it can not happen. Is there a well-known reason, that I'm not aware of, or is it a Chrome bug? It happens in Chrome DevTools when device mode is on. Steps to reproduce:

  1. Open the demo .
  2. Open DevTools in Chrome (F12).
  3. Enable device mode (CTRL+SHIFT+M).
  4. Reload the page (F5) to see the mobile style scroll bars.
  5. Click the right edge of the red child div to see "parent" instead "child".

If the demo is unavailable, here is the full code (doesn't work as a snippet):

<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>

        #parent {
      background: yellow;
      height: 200px;
      overflow: auto
    }
    #child {
      background: red;
      height: 250px;
    }


</style>
</head>
<body>

     <div id="parent">
      <div id="child"></div>
    </div>

<script>

      document.querySelector('#parent').addEventListener('click', function(event) {
      alert(event.target.id);
    });

</script>
</body>
</html>

It depends on which element you want to trigger for the event.

You can try switching to margin instead of padding so that there is a margin between the elements instead of padding of the child element.

You can also try looking at the event.currentTarget to see if that is what you intended to capture.

This other StackOverflow question may help as it includes a JSFiddle example.

A helpful diagram can be the box model for understanding the zones around an element: 在此处输入图片说明

因为有一个隐藏的滚动条,所以它属于父元素。

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