2016-02-13 92 views
1

我有一個SVG的代碼看起來像這樣的SVG元素使用Javascript以創建鼠標事件

<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來做這些事情,但我不知道。謝謝!

+0

在['d3.js'](https://d3js.org/)採取一個贓物。它使SVG動畫超級超級容易。 –

回答

0

這是一個香草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>