简体   繁体   中英

Finding the mouse pointer position relative to an svg element

I have a scg element written as below.

<svg height="300px" width="600px" xmlns="http://www.w3.org/2000/svg">
  <g id="100" onmouseout="outg()" style="stroke-width: 1;fill: rgb(255, 200, 200);">
   <rect height="25" rx="10" ry="10" style="fill: rgb(257, 87, 87);" width="160" x="330" y="35" />
    <text style="stroke: rgb(0, 0, 0);stroke-width: 1;" x="390" y="53" >ABC</text>
  </g>
</svg>

How do i determine if the mouse pointer is inside or outside the rectangle(but inside the svg). When I tried calling javascript functions with simple alerts for the onmouseout events for 'rect','g','text', it gets a bit confusing. Within the rectanle when I point over the text, technically the rectangle is exited and the text is entered.

I need to determine that the mouse pointer is completely out of the rectangle and this must happen only once, not on crossing over to the text area within the rectangle or out of the text area into the rectangle.

If you're using jQuery, you can make use of the jQuery mouseleave/mouseenter events, which do not have this problem.

the jQuery API docs describe it pretty well:

The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.

Source, with examples: http://api.jquery.com/mouseleave/

If you're not using jQuery and you're willing to do a bit of hacking, I'd suggest taking a look at the source for the jQuery mouseleave event , which will hopefully point you in the right direction.

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