Is it possible to navigate SVG object's elements from enclosing HTML?

后端 未结 4 2029
失恋的感觉
失恋的感觉 2020-12-31 23:41

I\'m loading an SVG through an object tag and need to access SVG\'s elements (to manipulate them). How can I do that?

Here\'re partial solutions I\'m aware of:

4条回答
  •  鱼传尺愫
    2021-01-01 00:13

    Here's a technique I have used successfully, mentioned in the (very good) O'Reilly "SVG Essentials" book:

    1. Add JavaScript code to your SVG document itself and handle the load event on the root svg element.

      
      
      
    2. In this svgScript.js load event handler, write out whatever you need to expose to the HTML-side script through the built-in parent variable.

      function init(evt) {
          svgDocument = evt.target.ownerDocument;
          parent.theSvgDocument = svgDocument;
      }
      
    3. Back in your HTML-side script, you can now directly access and use this reference.

      var svgDocument = theSvgDocument;
      

    In this example we expose the SVG Document object but you could pass on any object or a function. In my project I actually exposed some kind of controller object reference so that my SVG-side script contains all the logic for manipulating the SVG document, and the HTML-side script merely grabs this controller object and calls public methods on it.

提交回复
热议问题