问题描述
我对SVG很新,所以如果这是一个基本问题,请原谅我。
我想在屏幕上画圆圈并随时响应用户将鼠标放在每个圆圈上。
据我所知,当在svg上听鼠标事件时,我们实际上是在整个画布上听鼠标事件而不是如果我想处理形状上的事件,我必须使用像D3这样的库。
是否可以侦听鼠标指针经过特定圆圈时触发的mouseOver事件?
没有库需要这个。鉴于以下SVG:
< svg width =500height =500>
< circle id =circle1cx =50cy =50r =20fill =red/>
< circle id =circle2cx =150cy =50r =20fill =green/>
< / svg>
您可以使用CSS或Javascript让这些圈子以某种方式与鼠标相关联。
对于在css中的简单悬停,您可以执行以下操作:
#circle1:悬停{
填充:蓝色;
}
或者像这样的任何JavaScript鼠标事件:
document.getElementById('circle2')。addEventListener('click',function(e){
e.currentTarget.setAttribute('fill', '#ff00cc');
});
这是一个给你看看的演示:
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?
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
这篇关于鼠标悬停在SVG圈子上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!