Mouseover on SVG circles

2019-04-28 11:42发布

I'm very new to SVG, so please forgive me if this is a basic question.

I would like to draw circles on the screen and respond whenever the user mouses over each circle.

From what I can tell, when listening to mouse events on an svg, we are actually listening to mouse events on the whole canvas and not on the shapes.

If I want to handle events on the shapes, I have to use a library like D3.

Is it possible to listen to mouseOver event that are triggered when the mouse pointer passes over a specific circle?

3条回答
地球回转人心会变
2楼-- · 2019-04-28 12:06

Try this...

<circle onMouseMove={() => console.log('foo') }/>
查看更多
够拽才男人
3楼-- · 2019-04-28 12:09

No library is needed for this. Given the following SVG:

<svg width="500" height="500">

  <circle id="circle1" cx="50" cy="50" r="20" fill="red"/>
  <circle id="circle2" cx="150" cy="50" r="20" fill="green"/>

</svg>

You could use CSS or Javascript to have these circles change in some way related to the mouse.

For a simple hover in css you can do something like:

#circle1:hover {
  fill: blue;
}

Or any JavaScript mouse event like so:

document.getElementById('circle2').addEventListener('click', function(e) {
    e.currentTarget.setAttribute('fill', '#ff00cc');
});

Here is a demo for you to check out: http://codepen.io/ZevanRosser/pen/bdYyLp

查看更多
小情绪 Triste *
4楼-- · 2019-04-28 12:21

If you want this to only be svg and be able to open this in a browser and see the effect (although Zevan's answer can be embedded in svg), use something like:

<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500">
  <circle id="circle1" cx="50" cy="50" r="20" fill="red" onmouseover="evt.target.setAttribute('fill', 'blue');" onmouseout="evt.target.setAttribute('fill','red');"/>
  <circle id="circle2" cx="150" cy="50" r="20" fill="green" onmouseover="evt.target.setAttribute('fill', 'blue');" onmouseout="evt.target.setAttribute('fill','green');"/>
</svg>

the CSS option shared is cleaner, but this pattern may offer more flexibility for future mouse handling, especially if needing a function to figure out how long you want to let a user "pause" over the circle before actually modifying the property.

查看更多
登录 后发表回答