在SVG元素上使用Javascript以创建鼠标事件

Using Javascript on SVG elements in order to create mouse events

本文关键字:创建 鼠标 事件 Javascript SVG 元素      更新时间:2023-09-26

我有一个SVG代码,看起来像这样:

 <svg width="640" height="480" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
 <!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
 <g>
  <title>Layer 1</title>
  <rect id="svg_1" height="45" width="142" y="59.20001" x="59.39999" stroke-width="5" stroke="#000000" fill="#ffaaaa"/>
  <rect id="svg_2" height="56" width="142" y="217.20001" x="97.39999" stroke-width="5" stroke="#000000" fill="#ff007f"/>
  <rect id="svg_3" height="53" width="172" y="123.20001" x="360.39999" stroke-width="5" stroke="#000000" fill="#ff7f00"/>
 </g>
 </svg>

我想使用 Javascript 使所有单独的矩形在单击它们时略微移动。或者当我将光标悬停在它们上时显示某物的图片。我设法用CSS做到了,但我真的很有兴趣使用Javascript做这些事情,但我一无所知。谢谢!

这是一个普通的JavaScript起点。更新:整个代码中的注释解释了正在发生的事情。

var shapes = document.getElementsByTagName("rect"); // find all the shapes by making a collection of them
for (var i = 0; i < shapes.length; i += 1) { // tell the program what function (i.e. what handler)...
  shapes[i].addEventListener('click', clickHandler); // ...to run every time each shape is clicked
}
function clickHandler(event) { // the function to run when any shape is clicked
    // 'event' holds a lot of info, but critical here is 'which shape was clicked', i.e. event.target
  var inc = 4, iter = 0; // set the anim'n speed and the count of anim'n steps
  var jiggle = function() { // the function to perform on each animation cycle
    iter += 1; // increment the anim'n step count
    if (iter > 64) return; // when enough anim'n steps have run, do nothing more
    event.target.x.baseVal.value += inc; // animate! : change the shape's left pos'n
    if ((iter + 2) % 4 === 0) inc = -inc; // every 4 steps, change the move dir'n
    requestAnimationFrame(jiggle); // at the end of every anim'n step, do it all again
  };
  requestAnimationFrame(jiggle); // get the first step of the anim'n going
};
<p>Click the shapes</p>
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
 <!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
 <g>
  <title>Layer 1</title>
  <rect id="svg_1" height="45" width="142" y="59.20001" x="59.39999" stroke-width="5" stroke="#000000" fill="#ffaaaa"/>
  <rect id="svg_2" height="56" width="142" y="217.20001" x="97.39999" stroke-width="5" stroke="#000000" fill="#ff007f"/>
  <rect id="svg_3" height="53" width="172" y="123.20001" x="360.39999" stroke-width="5" stroke="#000000" fill="#ff7f00"/>
 </g>
 </svg>