简体   繁体   中英

How to pass a div position to a child element

I'm trying to pass the click position through to a child element of a div. In the following sample, I'm trying to pass the top and left co-ordinates of my-div through to the handleClick() function:

<div id="my-div">
    <div onclick={() => this.handleClick(this.offsetX, this.offsetY)} />

offsetX / y was my guess, but that doesn't seem to work. Is it possible to take the co-ordinates of the parent item and pass them through to a function of the child element?

You can try to do like this:

Function to handle the click:

 handleClick = e => {
    var rect = e.target.parentElement.getBoundingClientRect();
    console.log(rect);
 };

Element you want to get the coordinates:

  <div id="parent">
      <div id="child" onClick={e => this.handleClick(e)}>
        try this
      </div>
   </div>

rect will be an object containing the coordinates relative to the document and the dimension of the parent of the div you clicked.

Then you can use them as you like.

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