Add click event on elements of an embedded SVG in javascript

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

    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.

    
      
      
    
    

提交回复
热议问题