简体   繁体   中英

Why does clicking and dragging cause the parent element to be the `event.target`?

On a regular click of the child div , the following code will print the ID of that specific child div that was clicked.

<div id="parent">
  <div id="A" class="child"></div>
  <div id="B" class="child"></div>
</div>

<script>
  $("#parent").on('click', event => {
     $(event.target).text(event.target.id)
  })
</script>

However, if you click on one child div and drag/release in the other child div then it will print the ID of the parent element.

This does not occur when the click handler is assigned to the children.

$(".child").on('click', event => {
    $(event.target).text(event.target.id)
})

Why is the drag action causing the event target to be the parent element in the first example?

http://jsfiddle.net/thz1esfc/

Clarification on why not duplicate of What is event bubbling and capturing? :

I understand event bubbling and capturing is relevant to "why" but just stating that it is event bubbling or capturing does not explain the scenario. It does not explain why mousedown on child element A and mouseup from child element B would cause the parent element to be the event.target instead of child element A where the click started or child element B where the click is released.

These two seem to try to explain the results but I would like some documentation showing this behavior if possible.

Technically, browser register the CLICK on the parent b/c neither 1st or 2nd does not register complete CLICK (meaning mousedown and mouseup)

It's up to the browser to handle that behavior. On Firefox at least, the click event is lost when you click in one box, and drag to a different box and release.

This is happening to you because a click event is technically fired on release of the click and not on the actual click itself. See: https://developer.mozilla.org/en-US/docs/Web/Events/click

You can do mousedown and it will have a more accurate effect:

 $("#parent").on('mousedown', event => { $('#message').text(event.target.id) }) 
 #parent { width: 300px; height: 300px; background-color: cyan; } .child { height: 100px; width: 100px; background-color: grey; border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> <div id="1" class="child"> </div> <div id="2" class="child"> </div> </div> <p id="message"> </p> 

EDIT: comments are asking why when you click and drag to the next child to shows "parent" - this is event bubbling. You'd need to use event.stopPropagation() to stop that.

It's up to the browser to handle that behavior. On Firefox at least, the click event is lost when you click in one box, and drag to a different box and release.

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