Mouseover on SVG circles

前端 未结 3 996
不思量自难忘°
不思量自难忘° 2021-01-02 01:20

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 cir

相关标签:
3条回答
  • 2021-01-02 01:43

    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.

    0 讨论(0)
  • 2021-01-02 01:47

    Try this...

    <circle onmousemove={() => console.log('foo') }/>
    
    0 讨论(0)
  • 2021-01-02 02: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

    0 讨论(0)
提交回复
热议问题