Add click event on elements of an embedded SVG in javascript

前端 未结 5 1821
鱼传尺愫
鱼传尺愫 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:24

    Okay using your comments I found an answer to my problem. I added this code in the svg itself.

    <script type="text/javascript"> <![CDATA[
        function addClickEvents() {
            var countries = document.getElementById('svg1926').childNodes;
            var i;
            for (i=0;i<countries.length;i++){
                countries[i].addEventListener('click', showCountry);
            }
        }
    
        function showCountry(e) {
            var node = e.target;
            if (node.id != 'ocean') {
                node = getCorrectNode(node);
            }
            alert(node.id);
        }
    
        function getCorrectNode(node) {
            if (node.id.length == 2 || node.id == 'lakes') {
                return node;
            }
            return getCorrectNode(node.parentNode);
        }
    ]]> </script>
    

    The function addClickEvents is triggered when the svg loads. But I still have another problem with this. I have to embed this svg (with the code) into a HTML document using

    <embed src="circle1.svg" type="image/svg+xml" />
    

    Instead of alerting the id, I have to place it into a div in the HTML document. How do I get this id from the svg?

    0 讨论(0)
  • 2020-12-29 08:26

    If your SVG is contained in the DOM, you can attach event listeners to separate elements in the same manner as basic HTML. Using jQuery one example would be: http://jsfiddle.net/EzfwV/

    Update: Most modern browsers support inline svg, so to load your source into the DOM, all you have to do is load it in from a resource, (using something like jQuery's load()).

    Edit: more specific example http://jsfiddle.net/EzfwV/3/

    0 讨论(0)
  • 2020-12-29 08:31

    Here's an example that should be very similar to what you're trying to do. It uses <object> instead of <embed>, but that's only a minor detail. See this other example for how to get to the DOM of the embedded document from the parent document, it differs just a bit between the two.

    Also note that the svg maps that wikipedia have are quite large, so you will want to optimize the svgs before actual usage on a live website, try e.g SVG Cleaner or SVG Scour.

    0 讨论(0)
  • 2020-12-29 08:41

    Update July 2016

    It is possible to respond to events from embed elements now, under the condition that you embed something from the same domain. I have created a quick demonstration of this as a JSFiddle. The most important part is that it is possible to access the embedded document through embeddingElement.contentDocument. From there, the SVG element can be accessed and click event handlers can be installed.

    Implementation note: in the demo, I add event handlers to all path elements. For performance reasons, you would probably want to add a single event handler to the SVG and then use the event target in the handler. Edit: like in this updated Fiddle.

    Old answer

    A quick Google search brought me here. I think that's the answer to your problem, right?

    To summarize here: it is not possible to capture events on an embed element, unfortunately the only solution is modifying the SVG file.

    Here is a small example of how to embed JavaScript into an SVG file (JSFiddle). It is based on an example from IBM developerWorks.

    <svg>
      <script type="text/javascript">
        <![CDATA[
        var redVal = 0;
        var greenVal = 0;
        var blueVal = 0;
    
        function changeCol(evt) {
           redVal = Math.round(Math.random() * 255);
           greenVal = Math.round(Math.random() * 255);
           blueVal = Math.round(Math.random() * 255);
           evt.target.setAttribute("fill",
                 "rgb(" + redVal + "," + greenVal + "," + blueVal + ")");
    
        }
        // ]]>
      </script>
      <circle cx="200" cy="200" r="100" fill="blue"
              onclick="changeCol(evt)" />
    </svg>
    
    0 讨论(0)
  • 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

     <svg id="mySvg"></svg>
    

    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

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