简体   繁体   中英

How to get element ID + mouse button of clicked element?

I have a questions about AFrame events. When the user clicks with the mouse on an aframe element I want to know two things: 1) The ID of the clicked element and 2) which mouse button was used

To achieve this I've added an event listener to an aframe scene for the mousedown event (need this also for hover, mouseup etc in the future). When clicking on an aframe element the event listener is executed three times with a different parameter each time.

Object 1: contains ID of the aframe element/primitive that was clicked
Object 2: contains the aframe scene
Object 3: contains information about which mouse button was used ("which" attribute)

Looks like I have to combine the information from the first and the third execution of the eventlistener. This appears to be some kind of workaround, but not a smooth solution. Is this really the way to do it in AFrame? Are there situations where this could break? Is the order of the three executions guaranteed?

Example: https://codesandbox.io/s/n035zom4o4

Btw, I also tried to add an own event listener to every aframe element and not only to the box, but the problem still occurs.

Your listener is attached to the a-scene so you catch multiple bubbling events. Moreover, those created by the a-frame framework differ from the standard MouseEvent .

The button id is not kept in the a-frame s event wrapper, so you have to use the MouseEvent from listening to the document.

document.addEventListener("click", (e)=> {
  console.log(e.buttons) // button id
})

yet you need to check for the target id within the cursor component:

cursor.intersectedEl.id // cursor refers to the active cursor component

fiddle here

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