Add click event on elements of an embedded SVG in javascript

前端 未结 5 1819
鱼传尺愫
鱼传尺愫 2020-12-29 08:08

I got this SVG image from Wikipedia and embedded it into a website using this code:


5条回答
  •  囚心锁ツ
    2020-12-29 08:41

    A simple method is

    • Creating Path dynamically in SVG with javascript
    • Adding Styles Dynamically
    • Adding Events to Path
    • Appending to existing SVG.

    Script

     
    

    var XMAX = 500;
    var YMAX = 500;
    var _xx=10;
    var _reg=100;
    var _l=10;
    // Create PATH element
    for(var x=1;x<20;x++)
    {
    var pathEl = document.createElementNS("http://www.w3.org/2000/svg", "path");
    pathEl.setAttribute('d','M'+_l+' 100 Q 100  300 '+_l+' 500' );
    pathEl.style.stroke = 'rgb('+(_reg)+',0,0)';
    pathEl.style.strokeWidth = '5';
    pathEl.style.fill = 'none';
        $(pathEl).mousemove(function(evt){$(this).css({"strokeWidth":"3","stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#51c000"})});
    
    $('#mySvg').append(pathEl);
    _l+=50;
    }
    

    Live Demo in JSFiddle

提交回复
热议问题