Interactive SVG - how to choose element to react o

2019-09-09 20:09发布

问题:

I am trying to make an interactive SVG that would react on different user actions (mouse over, click etc.). I am using java Batik, but it will be enough, if you just describe me how to approach my problem in XML.

Clicking function works for me just fine. The problem is with hovering (mouse over action). My code looks like this:

svgRoot.setAttributeNS(null, "onmouseover", "evt.target.setAttribute('opacity', '0.5');");
svgRoot.setAttributeNS(null, "onmouseout", "evt.target.setAttribute('opacity', '1');");

svgRoot is the root node of my whole .svg file. All other elements are appended to it. When hovering over my svq, only the current element gets transparent (for example a text element or some rectangle I have currently mouse cursor on). However, I would like the whole svg be transparent (all elements). I thought that this would be done by appending this action to the root element, but its not.

I also have external ECMAscript file called "script.js" which is linked to every svg I create, so it is also possible for me to program this in this script, but I am not sure how.

Thanks for any tips.

回答1:

Say we have a circle with onmouseover and onmouseout trigger:

<circle id="mycircle" cx="100" cy="100" r="50" fill="blue" stroke="red" stroke-width="3" onmouseover="myOpacity(0.5)" onmouseout="myOpacity(1.0)"/>

And myOpacity() function in pure JS:-

function myOpacity(op_value) 
{
  myCircle = document.getElementById('mycircle');
  myCircle.setAttribute('opacity', op_value);
}

Note: You can also try onmousedown and onmouseup triggers.